4

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
loknomurze
  • 41
  • 2

2 Answers2

0

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);
}
Riccardo Galli
  • 12,419
  • 6
  • 64
  • 62
-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"))
t56k
  • 6,769
  • 9
  • 52
  • 115
  • 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"))` – loknomurze Dec 23 '21 at 08:17