gpt4 book ai didi

rust - 如何实现不跳过标记的类似 take_until_and_consume 的解析器组合器?

转载 作者:行者123 更新时间:2023-11-29 08:20:57 25 4
gpt4 key购买 nike

我想编写一个 nom 解析器组合器,它接受尽可能多的字节,包括标签序列。我尝试使用 take_until_and_consume!,但我发现生成的解析器组合器丢弃了标记序列:

#[macro_use]
extern crate nom;

named!(up_to_and_including_backslash, take_until_and_consume!("\\"));

fn main() {
let res = up_to_and_including_backslash(b" \\");
println!("{:?}", res);
}

结果:

Done([], [32, 32, 32, 32])

我希望在结果中包含标记序列(在本例中为反斜杠字符):

Done([], [32, 32, 32, 32, 92])

我怎样才能做到这一点?

最佳答案

更新:
您想在 take_until_and_consume!("\\") 上使用 recognize! 将它消耗的所有内容添加到输出。

你可以这样写你的解析器函数:

#[macro_use]
extern crate nom;

named!(up_to_and_including_backslash, recognize!( take_until_and_consume!("\\") ));

fn main() {
let res = up_to_and_including_backslash(b" \\");
println!("{:?}", res);
}

如果您需要将多个解析器使用的符号包含到您的输出中,您可以将它们全部放在 recognize! 中的 do_parse! 中。像这样:

recognize!( do_parse!( tag!("\\") >> take_until_and_consume!("\\") >> take!(4) >> () ) )

旧:
我让这个工作的唯一方法是这个丑陋的可憎。

named!(up_to_and_including_backslash,
do_parse!(
line: take_until_and_consume!("\\") >>
(
{
let mut complete_line:Vec<u8> = line.to_vec();
complete_line.extend_from_slice(b"\\");
&*complete_line
}
)
)
);

关于rust - 如何实现不跳过标记的类似 take_until_and_consume 的解析器组合器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47379729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com