Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all if else and else if statements with no parentheses

Tags:

c#

regex

I've got a bunch of code in c# that has here and there lines where an if or else statement without parentheses got some extra lines which result in false behavior. I am looking for a regex to find all possible places where this problem could occur so i can manually look for it.

To clarify what i mean. In code are a few places (i found until now) where the following code is wrong.

if (notInitialized)
    Initialize();
    AdditionalInitializationNotUseThisWhenAlreadyInitialized();

which should be

if (notInitialized) {
    Initialize();
    AdditionalInitializationNotUseThisWhenAlreadyInitialized();
}

I tried this if\s*\(.*\)([\n\r\s[^{]]*.*);* but it gives me not only the results i want. It has the if (notInitialized) { parts too. I have almost no experience in using regex.

How can i find all these cases without checking every if/else/else if in the code, just the ones without curly braces?

like image 617
Booser Avatar asked Dec 19 '25 06:12

Booser


1 Answers

One problem you are facing is that the regex is matching as much as it can on the .* to find a pattern match. Therefore, and depending on the options used (e.g. . matches anything but \n, or anything), you'll get unsatisfactory results.

Another problem is that you'd need to match recursively, e.g. skip as many ) as there were nested '(' in the expression. Only a very few regex engines can do this; .NET fortunately can via "balancing groups" but it is tricky and highly advanced application of regex. Also, for that to work correctly, you'd have to also recognize string and character literals (in quotes) as to not count parens in these.

Edit This regex for .NET should pretty reliably find these if and else statements:

\b(if\s*\(((?:[^()"']|'(\\.|[^'\\])'|"(\\.|[^"\\])"|(?<parens>\()|(?<-parens>\)))*(?(parens)(?!))\))|else)\s*[^{\s]

While this shows how powerful regexes can be, it's very cryptic and the proper way to do this would really be with a real parser (such as Roslyn).

like image 180
Lucero Avatar answered Dec 20 '25 19:12

Lucero