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”).

Leave a Comment