With regex in Java, I want to write a regex that will match if and only if the pattern is not preceded by certain characters. For example:
JavaScript
x
String s = "foobar barbar beachbar crowbar bar ";
I want to match if bar
is not preceded by foo
. So the output would be:
JavaScript
barbar
beachbar
crowbar
bar
Advertisement
Answer
You want to use negative lookbehind
like this:
JavaScript
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”).