Reputation: 660
Is there a general regex for matching one string, but only if a line does not contain another string?
E.g I want to match the word apple
but only if the line does not contain banana
. So the following lines:
apple banana
- does not matchpear apple
- matches apple but not pear apple pear apple
- matches the first and second apple but not the pear I know that
^((?!banana).)*$
will match a line that does not contain banana. But I can't seem to combine that with matching apple only.
Upvotes: 2
Views: 477
Reputation: 174726
You could try this regex,
(?<!banana.)\b(?!.*banana)apple\b
OR
.*?banana.*|\b(apple)\b
This would capture the string apple
on the lines where the string banana
isn't exists.
Upvotes: 1
Reputation: 785286
You can use this PCRE regex:
.*banana.*$(*SKIP)(*F)|\bapple\b
Upvotes: 4
Reputation: 420
Can't comment because I don't have enough reputation yet. But just to add to anubhava's answer so something like banana apple banana will work:
\b(?!.*banana)apple\b(?!.*banana)
EDIT:
You're right; Avinash Raj's answer looks like it works though.
Upvotes: 1