How to use nom to parse until a string is found?
Asked Answered
P

2

6

It's easy to use nom to parse a string until a character is found. How to use nom to gobble a string until a delimiter or the end? deals with this.

How do I do the same with a string (multiple characters) instead of a single delimiter?

For example, to parse abchello, I want to parse everything until hello is found.

Pushup answered 22/12, 2021 at 15:28 Comment(0)
B
1

take_until parse everything up to the provided string, excluded.

use nom::{bytes::complete::take_until, IResult};

fn parser(s: &str) -> IResult<&str, &str> {
    take_until("hello")(s)
}

fn main() {
    let result = parser("abchello");
    assert_eq!(Ok(("hello", "abc")), result);
}
Burseraceous answered 23/4, 2022 at 4:2 Comment(0)
S
-1

This code returns the correct result.

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);
}

The documentation is here.

cargo run
-> Ok(("hello", "abc"))
Stagger answered 22/12, 2021 at 23:16 Comment(1)
This is wrong. "The parser will return the longest slice till one of the characters of the combinator’s argument are met.". parser("abch123"); gives Ok(("h123", "abc"))Pushup

© 2022 - 2024 — McMap. All rights reserved.