Search code examples
regexnegative-lookbehind

Multiple negative lookbehind with 2-3 words between and commas


consider that I want to get the phrases that contain party and have been great!.

Therefore, the cases I am missing are those with commas or points that mark a separation between sentences (1) or a maximum of 2 or 3 words between the no|bad and the party (2).

This is my current regex.

(?<!\b(no|bad)\b.*)party

is there any party?  --> ok
no party --> ok
it was a bad and poor party --> ok
oh, this was a bad party --> ok
no man, this was great party --> BAD (1) (consider the comma or a point that means end sentence)
no sir it was indeed a barbaric party --> BAD (2) (consider a maximum of two or tree words between no|bad and party)

Solution

  • You may use

    (?<!\b(?:no|bad)\b(?:[^,\w]+\w+){0,2}[^,\w]+)\bparty\b
    

    See the regex demo.

    Details:

    • (?<!\b(?:no|bad)\b(?:[^,\w]+\w+){0,2}[^,\w]*) - a negative lookbehind failing the match if, immediately to the left of the current location, there is
      • \b(?:no|bad)\b - a whole word no or bad
      • (?:[^,\w]+\w+){0,2} - zero, one or two occurrences of any 1+ chars other than a comma or word chars and then one or more word chars
      • [^,\w]+ - and then one or more chars other than , and word chars.
    • \bparty\b - a whole word party.