0

I am attempting to write a regex that match words containing "foo" or "bar" but not "baz" anywhere in the string.

/(foo|bar).*(?!baz)/

How do I achieve that?

Nemo
  • 20,986
  • 9
  • 41
  • 56

1 Answers1

1

You may use this regex:

^(?!.*\bbaz\b).*\b(?:foo|bar)\b

(?!.*\bbaz\b) is negative lookahead condition to fail the match if word baz is found anywhere in your input.

RegEx Demo

anubhava
  • 664,788
  • 59
  • 469
  • 547