【问题标题】:How to use nom to parse until a string is found?如何使用 nom 进行解析,直到找到一个字符串?
【发布时间】:2026-01-10 02:35:01
【问题描述】:

很容易使用 nom 来解析一个字符串,直到找到一个字符。 How to use nom to gobble a string until a delimiter or the end? 处理这个问题。

如何对字符串(多个字符)而不是单个分隔符执行相同操作?

例如,要解析abchello,我想解析所有内容,直到找到hello

【问题讨论】:

    标签: rust nom


    【解决方案1】:

    此代码返回正确的结果。

    use nom::{IResult, bytes::complete::is_not};
    
    fn parser(s: &str) -> IResult<&str, &str> {
      is_not("hello")(s)
    }
    
    fn main() {
        let result = parser("abchello");
        println!("{:?}", result);
    }
    

    文档是here

    cargo run
    -> Ok(("hello", "abc"))
    

    【讨论】:

    • 这是错误的。 “解析器将返回最长的切片,直到满足组合器参数的字符之一。”。 parser("abch123");Ok(("h123", "abc"))