gpt4 book ai didi

使用 nom 解析驼峰式字符串

转载 作者:行者123 更新时间:2023-11-29 08:06:17 35 4
gpt4 key购买 nike

我想将像 "ParseThis""parseThis" 这样的字符串解析成像 ["Parse", "This"]< ​​这样的字符串向量["parse", "this"] 使用 nom crate。

我尝试过的所有尝试都没有返回预期的结果。可能我还不明白如何使用 nom 中的所有功能。

我试过:

named!(camel_case<(&str)>, 
map_res!(
take_till!(is_not_uppercase),
std::str::from_utf8));

named!(p_camel_case<&[u8], Vec<&str>>,
many0!(camel_case));

但是 p_camel_case 只返回一个 Error(Many0) 来解析以大写字母开头的字符串,解析以小写字母开头的字符串时返回 Done 但结果为空字符串。

我如何告诉 nom 我要解析字符串,用大写字母分隔(假设可以有第一个大写或小写字母)?

最佳答案

您要查找以任意字符开头,后跟一些非大写字母的内容。作为正则表达式,它看起来类似于 .[a-z]*。直接翻译成 nom,就像这样:

#[macro_use]
extern crate nom;

use nom::anychar;

fn is_uppercase(a: u8) -> bool { (a as char).is_uppercase() }

named!(char_and_more_char<()>, do_parse!(
anychar >>
take_till!(is_uppercase) >>
()
));

named!(camel_case<(&str)>, map_res!(recognize!(char_and_more_char), std::str::from_utf8));

named!(p_camel_case<&[u8], Vec<&str>>, many0!(camel_case));

fn main() {
println!("{:?}", p_camel_case(b"helloWorld"));
// Done([], ["hello", "World"])

println!("{:?}", p_camel_case(b"HelloWorld"));
// Done([], ["Hello", "World"])
}

当然,您可能需要小心实际匹配正确的非 ASCII 字节,但您应该能够以直接的方式扩展它。

关于使用 nom 解析驼峰式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183708/

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