Search code examples
regexregex-lookarounds

regex lookahead matching keyword and excluding a specific pattern ahead


I want regex to match the whole sentence after any ERROR (including ERROR itself) except when ERROR is followed by MO already exists. So for example in below I want the whole lines of 1,2,3,4 but nothing from line 5.

ERROR  
we have an ERROR here da da da  
ERROR Parent MO not found  
ERROR anything else is here  
ERROR MO already exists 

I have tried below lookahead in regex to match the desired pattern but not fully achieved what I wanted.
ERROR (?!MO already exist)
What modification do I need?


Solution

  • With your shown samples could you please try following. Onlie demo Online regex demo

    ERROR\s+(?!MO already exist).*$
    

    Explanation: Looking for ERROR space(s) then checking negative look ahead to make sure it doesn't have MO already exist and matching everything till end of line here.

    NOTE: OR in case you can have more than one spaces between MO already exists then try following.

    ERROR\s+(?!MO\s+already\s+exist).*$