I've got quite a lot of code in which sometimes if-statements have been written, without a matching else-statement. In some places, this is an issue, because when something fails, the failure is not handled correctly. I want to manually confirm all places an if-without-an-else occurs.
I've tried using regex, but I haven't succeeded in finding a way to match the right bracket, since regex cannot really handle nested brackets.
The code I want to find looks like this:
if( ... ) {
...
}
The code I don't want to find, looks like this:
if( ... ) {
...
} 
else {
... 
}
How can I list all these places, so I can go through them?
                        
As you noticed by yourself, generally this has to be done with some sort of parser. With regex it's simply just pain and there are a lot of parser / grammar modules out there.
I created a one time solution script (in nodejs), which uses regex and the number of indents for matching starting to closing
if / elsestatements. It works if following conditions are fullfilled:ifhas the same numbers of indents as the closingelsethis works:
this does NOT work:
ifandelseon the same line ! (should not be ususally..)Here's the script i came up with, it stores all line numbers with an
ifwhich does not have anelse. U can check line numbers and click on a givenif, then vs code highlights the ending parenthesis and you can add theelse. It uses lodash but only for flattening results in the end. It's not truely dependent..I tested it with this code:
Results =>
final lines: [ 2, 4, 29, 34, 45 ]You may wanna test a little bit more before using it ! But it should work when the indents are correct. This article is also related and nice to read! => why you should not use regex to parse tree structures....