Jaime
Jaime

Reputation: 605

Regex ignore everything between 2 words

I have some strings to check against a Regex pattern. Here is the regex:

apple(?!( ?not)).*?inc(\.|luded)?

string 1: "banana, rotten apple not included" - does not give me a match which is what I want.

string 2: "banana, rotten apple included" - produces a match which is what I want

But if I have a string like...

"banana, rotten apple, ripe avocado not included" or "banana, rotten apple and apricot not included" both produces a match which I don't want.

So basically, I want to see if both "apple" and "included" (or "inc" or "inc.") are in the string and NO "not" before "included" and ignore everything else in between.

Thanks!

Upvotes: 0

Views: 8572

Answers (2)

Tim Sylvester
Tim Sylvester

Reputation: 23128

How about:

apple.*(?<!\snot)\s+inc(\.|luded)

Upvotes: 3

Phil
Phil

Reputation: 4867

You're using a negative lookahead assertion that verifies that "not" does not appear right after "apple". But, if I understand you correctly, what you want is to check that "inc" is not immediately preceded by "not". You can use a negative lookbehind assertion, like the following:

apple.*(?<!(\bnot ))inc(\.|luded)?

Upvotes: 3

Related Questions