I need a regex that will match blahfooblah
but not blahfoobarblah
I want it to match only foo and everything around foo, as long as it isn't followed by bar.
I tried using this: foo.*(?<!bar)
which is fairly close, but it matches blahfoobarblah
. The negative look behind needs to match anything and not just bar.
The specific language I'm using is Clojure which uses Java regexes under the hood.
EDIT: More specifically, I also need it to pass blahfooblahfoobarblah
but not blahfoobarblahblah
.
Best Answer
Try:
Tests:
Regular expression explanation
Other regex
If you only want to exclude
bar
when it is directly afterfoo
, you can useEdit
You made an update to your question to make it specific.
New tests
New explanation
(?=.*foo(?!bar))
ensures afoo
is found but is not followed directlybar