I'm trying to create a simple regex where I need to capture all the Dogs occurrences as long as it is not preceded by another word Cats. Here are some examples to test the regex:
I'm trying with a regex similar to this:
((?<!\bCats\b)\s*\bDogs\b)
Which doesn't give the right results (it matches all cases when it should not match the 3rd case)
Also, if I use something similar:
((?<!\bCats\b)\s+\bDogs\b)
It returns the right result for cases 1 and 3, but it does Not match case 2 since Dogs was found at the beginning and it is not preceded by white space.
Case sensitivity is not a problem here. I'm using Java to test this regex
If I understand your requirements clearly then you may use this regex with a negative lookahead instead of lookbehind:
^(?!.*\bCats\s+Dogs\b).*?\bDogs\b
RegEx Details:
^
: Start(?!.*\bCats\s+Dogs\b)
: Negative lookahead to fail the match if we find word Cats
followed by 1+ whitespace followed by word Dogs
anywhere.*?\bDogs\b
: Match word Dogs
after 0 or more characters