使用 nom 捕获整个连续的匹配输入

Capture the entire contiguous matched input with nom

我正在寻找应用一系列 nom parsers and return the complete &str that matches. I want to match strings of the form a+bc+. Using the existing chain! macro 我可以非常接近:

named!(aaabccc <&[u8], &str>,
   map_res!(
       chain!(
           a: take_while!(is_a) ~
               tag!("b") ~
               take_while!(is_c) ,
           || {a}
           ),
       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,
    }
}

假设我们有 'aaabccc' 作为输入。上面的解析器将匹配输入,但只有 'aaa' 会被 returned。我想做的是 return 'aaabccc',原始输入。

chain! 不是正确的宏,但没有另一个看起来更正确。最好的方法是什么?


在撰写本文时,我正在使用 nom 1.2.2 和 rustc 1.9.0-nightly (a1e29daf1 2016-03-25)

看来你想要recognized!:

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

还有一个例子:

#[macro_use]
extern crate nom;

use nom::IResult;

fn main() {
    assert_eq!(aaabccc(b"aaabcccddd"), IResult::Done(&b"ddd"[..], "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,
    }
}

如果您不关心这些值,我不确定 chain! 是否是组合顺序解析器的最佳方式,但它在这种情况下有效。