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

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.



Solution 1:[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);
}

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Riccardo Galli
Solution 2 t56k