I'm trying to match a word (good) if another word (bad) does not exist in the same sentence. I want to do this using lookaround as I want only the first word (good) to be included in the captured results.
Here's my regular expression:
(?<!\bbad\b[^.])\bgood\b(?![^.]+\bbad\b)
This does work in all cases except when the word I'm looking for (good) precedes the other word (bad).
So in the following examples, the results are as follows:
Can someone please point me to what I'm missing here? Here's my test on regex101.com.
You may use this regex:
(?:^|\.)(?:(?!\b(?:bad|good)\b)[^.])*(\bgood\b)(?![^.]+\bbad\b)
RegEx Demo
RegEx Details:
(?:^|\.): Match start position or a dot(?:(?!\b(?:bad|good)\b)[^.])*: Match a non dot character if doesn't have word good or bad ahead. Repeat this match 0 or more times(\bgood\b): Match full word good(?![^.]+\bbad\b): Negative lookahead to assert that we don't have one or more non-dot characters followed by the word, bad ahead of the current positionIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With