badger5000
badger5000

Reputation: 660

regex match one string only if line does not contain another string

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:

  1. apple banana - does not match
  2. pear apple - matches apple but not pear
  3. 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

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174726

You could try this regex,

(?<!banana.)\b(?!.*banana)apple\b

DEMO

OR

.*?banana.*|\b(apple)\b

This would capture the string apple on the lines where the string banana isn't exists.

DEMO

Upvotes: 1

anubhava
anubhava

Reputation: 785286

You can use this PCRE regex:

.*banana.*$(*SKIP)(*F)|\bapple\b

Working Demo

Upvotes: 4

Othya
Othya

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

Related Questions