Regular Expression – Where string contains ‘bar’ but is not preceded by ‘foo’

regex

I currently have a regular expression to match where a string contains 'bar' but is not preceded by 'foo':

(?<!foo)bar

I wish to modify the regex to match where a string contains 'bar' but is not preceded by 'foo' and (optionally) any additional character(s).

EG. 'footestbar' should not match as bar is preceded by 'foo' followed by 'test'.

I cannot find a way to achieve this as regular expressions do not permit the use of a quantifier within a negative lookbehind. Subsequently I cannot do the following:

(?<!foo.*)bar

Is there an alternative approach?

UPDATE:
The regular expression flavour is re2. I am currently reviewing the documentation, but on first glance have noticed the following:

(?<!re)     after text not matching re (NOT SUPPORTED)

Therefore the solution cannot use a negative lookbehind (if I'm interpreting the documentation correctly).

Best Answer

Amended Post

So it would seem that some (most?) Regex engines only work with a fixed length lookbehind. However, they seem fine to accept a variable length lookahead. I'm not sure what your use case for this is or how viable it would be, but one idea could be to reverse your string, and use:

rab(?!.*oof)

enter image description here

Of course, it looks ridiculous, and I don't know how your using it or how useful it will be. Most of my experience with Regex has been using .NET, and mostly not needed lookbehinds. Just an idea for you..!

Original Post - Only works with certain Regex engines (Tested using .NET)

Try the following regex:

(?<!foo(?:.*)?)bar

This adds an optional, non capturing group within the same negative look behind.

enter image description here

Related Question