2

How can I create a negative lookahead parser for nom?

For example, I'd like to parse "hello", except if it's followed by " world". The equivalent regex would be hello(?! world).

I tried to combine the cond, not and peek parsers

fn parser(input: &str) -> IResult<&str, &str> {
    cond(peek(not(tag(" world"))(input)), tag("hello"))(input)
}

but this doesn't work as cond expects the condition as bool instead of as IResult.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
mdcq
  • 1,593
  • 13
  • 30
  • `not()` is generally something a parser combinator should avoid to use. It kind of the opposite of what a parser combinator is for – Stargateur Feb 06 '23 at 19:34

1 Answers1

2

Try using terminated()

terminated(tag("hello"), not(tag(" world")))
mdcq
  • 1,593
  • 13
  • 30
MeetTitan
  • 3,383
  • 1
  • 13
  • 26