Search code examples
regexnegative-lookbehind

How to regex with negative search?


I want to search a document for the following string

<whoName>[substring]</whoName>

where substring != "self"

so

<whoName>other</whoName> 

would pass.

but

<whoName>self</whoName> 

would fail


Solution

  • You can use this negative lookahead based regex:

    <(whoName)>(?!self\s*<).*?<\/\1>
    

    RegEx Demo

    Regex breakup:

    <(whoName)>  # Match <whoName> and capture it ($1)
    (?!self\s*<) # Negative lookahead that means current position is not followed by literal 
                 # self followed by 0 or more spaces and <
    .*?          # Match 0 or more characters (non-greedy)
    <\/\1>       # Match closing tag using back-reference to captured group #1