Andy
Andy

Reputation: 46404

Another question on negative regex

I have a python script that checks code for coding convention errors. It does this by matching a regex that represents a violation of the coding standard.

One of our standards is that 'if', 'while' and 'do-while' conditionals must contain a conditional operator.

So no

if (var1)
{
    // blah
}

Instead I need

if (var1 == TRUE)
{
    // blah
}

For example, what I need for if statements is to match "if" at the beginning of the line, and find the situation when it doesn't contain "==", "<=", ">=", "||" or "&&" anywhere after it. I've been pounding my head against the wall for a few hours and I'm hoping someone here can alleviate some of the pain!

Upvotes: 1

Views: 190

Answers (2)

Andy
Andy

Reputation: 46404

Here is what I ended up doing, it works fairly well for the most part, not ideal though and we are looking into a third party parser.

^\s*\bif\s*\(\s*\w+\s*\)\s*$

Upvotes: 0

aeter
aeter

Reputation: 12700

This could do it for the input you provided, but as mentioned in the comments, it's better using a parser (e.g. pyparsing).

>>> s
'if (var1)'
>>> s2
'if (var1 == TRUE)'
>>> if re.search(r"^if.+==|<=|>=|\|\||&&", s): print "found bad signs"
... 
>>> if re.search(r"^if.+==|<=|>=|\|\||&&", s2): print "found bad signs"
... 
found bad signs

Upvotes: 1

Related Questions