227
votes

So 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:

String s = "foobar barbar beachbar crowbar bar ";

I want to match if bar is not preceded by foo. So output would be:

barbar
beachbar
crowbar
bar

I know this is probably a very simple question. I am trying to learn regex, but in the meantime I need something to work now.

2

2 Answers

370
votes

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

1
votes

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