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
  • 24,540
  • 12
  • 45
  • 61

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
  • 761,203
  • 64
  • 569
  • 643