How to use nom to parse until a string is found?

Viewed 390

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.

2 Answers

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

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"))
Related