Reputation: 138
With this expression: .*(?=good)
i can get:
text is good -> text is
But how to supplement this expression so that it also work in the following case:
text is not good -> NOT MATCH or empty string
Upvotes: 0
Views: 919
Reputation: 633
You could use a negative Lookbehind:
.+(?<!not )(?=good)
This ensures that the position where the Lookahead starts is not preceded by "not "
.
Demo.
If you want to make sure that the word "not" doesn't appear anywhere before the Lookahead, you may use:
^(?:(?!not).)+(?=good)
Demo.
And if you want to make sure that the word "not" doesn't appear anywhere in the string (even after the Lookahead), you may use:
^(?!.*not).+(?=good)
Demo.
P.S. Use \bnot\b
if the rejected "not" must be a whole word (e.g., if you want to allow "knot").
Upvotes: 4
Reputation: 163287
You can assert from the start of the string that it does not contain not good
Then use a non greedy quantifier to match until the first occurrence of good
to the right (In case good occurs more than once)
^(?!.*\bnot good\b).*?(?= good\b)
Explanation
^
Start of string(?!
Negative lookahead
.*\bnot good\b
Match not good
between word boundaries)
Close lookahead.*?
Match any char as least as possible (In case of more occurrences of good
, stop before the first)(?= good\b)
Positive lookahead, assert good
at the rightUpvotes: 2