Search code examples
pythonpython-3.xregexregex-lookarounds

Negative look ahead matching when it should not match


I made this regex to match var being read

\bvar\b([^;^{]*?([\s]*?([<]|[>]|[!]|[=]{2})))([^;]*?)(?!=)

These are my test strings:

var->var1 = blah;     //must not match -but matches
var = 8;              //as expected - do not match          
if(var >= 9)          //as expected - matches
if(var ->var1 == balh) //as expected - matches

See here

(([<]|[>]|[!]|[=]{2}) checks for the presence of >,<,! or ==)

My issue is that it should match (no need to get the result) when var is read, not written. But when var-> comes in my test string, it automatically matches because of [>] in my regex. I tried negative lookahead ([^;]*?)(?!=) .But this does not do anything to my original regex.


Solution

  • You can fix the current expression using

    \bvar\b(?!->)(?=[^;^{]*(?:[<>!]|==))
    

    See the regex demo.

    Details:

    • \bvar\b - a whole word var
    • (?!->) - -> immediately to the right of the current location is not allowed
    • (?=[^;^{]*(?:[<>!]|==)) - immediately to the right of the current location, there must be any zero or more chars other than ;, ^, and { and then <, >, !, or ==.