regex to match words but not if a certain phrase

Question:

In python, I want to match substring containing two terms with up to a certain number of words in between but not when it is equal to a certain substring.

I have this regular expression (regex101) that does the first part of the job, matching two terms with up to a certain number of words in between.

But I want to add a part or condition with AND operator to exclude a specific sentence like "my very funny words"

 my(?:s+w+){0,2}s+words

Expected results for this input:

I'm searching for my whatever funny words inside this text

should match with my whatever funny words

while for this input:

I'm searching for my very funny words inside this text

there should be no match

Thank you all for helping out

Asked By: Mag_Amine

||

Answers:

You may use the following regex pattern:

my(?! very funny)(?:s+w+){0,2}s+words

This inserts a negative lookahead (?! very funny) into your existing pattern to exclude the matches you don’t want. Here is a working demo.

Answered By: Tim Biegeleisen