Regex for matching something if it is not preceded by something else Regex for matching something if it is not preceded by something else java java

Regex for matching something if it is not preceded by something else


You want to use negative lookbehind like this:

\w*(?<!foo)bar

Where (?<!x) means "only if it doesn't have "x" before this point".

See Regular Expressions - Lookaround for more information.

Edit: added the \w* to capture the characters before (e.g. "beach").


Another option is to first match optional word characters followed by bar, and when that has matched check what is directly to the left is not foobar.

The lookbehind assertion will run after matching bar first.

\w*bar(?<!foobar)
  • \w* Match 0+ word characters
  • bar Match literally
  • (?<!foobar) Negative lookbehind, assert from the current position foobar is not directly to the left.

Regex demo