Capture the entire contiguous matched input with nom

后端 未结 1 748
说谎
说谎 2021-01-13 06:59

I\'m looking to apply a series of nom parsers and return the complete &str that matches. I want to match strings of the form a+bc+. Using the e

相关标签:
1条回答
  • 2021-01-13 07:27

    It appears as if you want recognized!:

    if the child parser was successful, return the consumed input as produced value

    And an example:

    #[macro_use]
    extern crate nom;
    
    use nom::IResult;
    
    fn main() {
        assert_eq!(aaabccc(b"aaabcccffffd"), IResult::Done(&b"ffffd"[..], "aaabccc"));
    }
    
    named!(aaabccc <&[u8], &str>,
       map_res!(
           recognize!(
               chain!(
                   take_while!(is_a) ~
                   tag!("b") ~
                   take_while!(is_c),
                   || {}
               )
           ),
           std::str::from_utf8
       )
    );
    
    fn is_a(l: u8) -> bool {
       match l {
           b'a' => true,
           _ => false,
       }
    }
    
    fn is_c(l: u8) -> bool {
        match l {
            b'c' => true,
            _ => false,
        }
    }
    

    I'm not sure if chain! is the best way of combining sequential parsers if you don't care for the values, but it works in this case.

    0 讨论(0)
提交回复
热议问题