使用 nom 解析驼峰式字符串

标签 parsing rust nom

我想将像 "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/

相关文章:

rust - 将Box与nom解析器一起使用时出现神秘错误 “one type is more general than the other”

c# - 用于 C# 开发的 Visual Studio 插件

function - 如何从程序集中调用 Rust 函数?

rust - 有没有办法可以将 futures 0.1 转换为标准库 futures?

vector - 如何创建堆栈分配的类似矢量的容器?

rust - 如何在 nom 中取 N 位字节?

rust - nom::bits::bits返回的剩余数据不正确

javascript - Node.js:从 JSON 响应中提取数据

python - 如何使用 RegEx 加速 Apache 日志的解析以扩展 Pandas 数据框?

python - 解析问题