In our Java Selenium framework, we need to write a regex that reads a string of any length and returns true if it contains the substring "bar" so long as the substring "foo" doesn't appear in the string by using a Negative Lookaround by combining a Negative Lookbehind with a Negative Lookahead.
The best regex I can construct is (?<!foo)bar(?!.*foo).*
It correctly matches the following desirable strings:
bar
,bar,
,,bar,,
barbar
,bar,bar,
,,bar,,bar,,
barbarbar
,bar,bar,bar,
,,bar,,bar,,bar,,
However, it also matches the following undesirable strings:
,foo,bar,
,,foo,,bar,,
foobarbar
,foo,bar,bar,
,,foo,,bar,,bar,,
,bar,foo,bar,
,,bar,,foo,,bar,,
,foo,foo,bar,
,,foo,,foo,,bar,,
My testing was conducted here: https://regex101.com/r/uhdUhU/5
@CAustin and @CarySwoveland have kindly provided the right answer: ^(?!.*foo).*bar
^
asserts position at start of a line
(?!.*foo)
is the Negative Lookahead
.
matches any character (except for line terminators)
*
matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Answer verified here: https://regex101.com/r/OzHZ1k/3