使用 nom 捕获整个连续匹配的输入 [英] Capture the entire contiguous matched input with nom

查看:23
本文介绍了使用 nom 捕获整个连续匹配的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望应用一系列 nom 解析器并返回完整的 &str 匹配.我想匹配 a+bc+ 形式的字符串.使用现有的 chain! 我可以得到非常接近:

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 existing chain! macro I can get pretty close:

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".我想做的是返回原始输入aaabccc".

Say we have 'aaabccc' as input. The above parser will match the input but only 'aaa' will be returned. What I would like to do is return 'aaabccc', the original input.

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

chain! is not the right macro for this, but there was not another that seemed more correct. What would the best way to do this be?

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

At the time of this writing I'm using nom 1.2.2 and rustc 1.9.0-nightly (a1e29daf1 2016-03-25).

推荐答案

看起来好像你想要 已识别!:

It appears as if you want 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! 是否是组合顺序解析器的最佳方式,但它在这种情况下有效.

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.

这篇关于使用 nom 捕获整个连续匹配的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆