gpt4 book ai didi

rust 标称 : many and end of input

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

我正在尝试熟悉 Nom,目前是第 5 版,其中没有 CompleteStr 和其他内容,因此相关问题不是很有帮助。

我怎样才能解析类似的东西

"@pook Some free text @another_pook And another text"

进入

vec![("pook", "Some free text"), ("another_pook", "And another text")]

?

@ 前缀的字符串称为“字段标识符”;下一个子串是描述;都叫“场”

下面是我如何成功解析一个字段:

use nom::bytes::complete::take_while1;
use nom::*;
use nom::character::is_alphabetic;

fn ident(c: char) -> bool {
is_alphabetic(c as u8) || c == '_'
}

fn freetext(c: char) -> bool {
c != '@'
}

fn parse_ident(s: &str) -> IResult<&str, &str> {
take_while1(ident)(s)
}

fn parse_freetext(s: &str) -> IResult<&str, &str> {
take_while1(freetext)(s)
}


named! {field_ident<&str, &str>,
do_parse!(
tag!("@") >>
name: parse_ident >>
(name)
)
}

named! { field <&str, (&str, &str)>,
do_parse!(
name: ws!(field_ident) >>
description: parse_freetext >>
(name, description)
)
}

当我将它包装到 many1 中并按照开头所述提供输入时,我收到了 Err(Incomplete(Size(1))),但如果我输入它,它就会工作@ 在输入的末尾。如何在输入结束时将其标记为已完成?

最佳答案

您需要 many_till 组合器,而不是 many1,如下所示:

use nom::bytes::complete::take_while1;
use nom::character::is_alphabetic;
use nom::*;

fn ident(c: char) -> bool {
is_alphabetic(c as u8) || c == '_'
}

fn freetext(c: char) -> bool {
c != '@'
}

fn parse_ident(s: &str) -> IResult<&str, &str> {
take_while1(ident)(s)
}

fn parse_freetext(s: &str) -> IResult<&str, &str> {
take_while1(freetext)(s)
}

named! {field_ident<&str, &str>,
do_parse!(
tag!("@") >>
name: parse_ident >>
(name)
)
}

named! { field <&str, (&str, &str)>,
do_parse!(
name: ws!(field_ident) >>
description: parse_freetext >>
(name, description)
)
}

named!(fields<&str, (Vec<(&str, &str)>, &str)>, many_till!(field, eof!()));

fn main() {
println!("{:?}", field("@pook Some free text"));
println!(
"{:?}",
fields("@pook Some free text @another_pook And another text")
);
}

相当反直觉。我猜这与 nom 的流媒体特性有关。

关于 rust 标称 : many and end of input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57608442/

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