-3
votes

I am trying to develop a regular expression that will match everything within a python if statement, and the like. So far I have the beginning match as ':[\n][\t]' , but I am not able to figure out the regex to detect the closing of an if statement in python. So far the best I could come up with is [\n][^\t] because I know that a block is exited when a newline is not followed by a tab.

1
Have you considered using ast instead? - roippi
Actually, a block is exited when the indentation goes down. Tabs aren't required. - Tom Zych
This is difficult in the general case. Consider comments (that can be at the LH boundary) and here documents as just two difficulties among many. As roippi states -- use ast - dawg
@TomZych: a block is exited when the indentation goes down Not always. Comments can be any indentation - dawg
assuming that everything will be tabbed properly and comments are not considered, is there a way? - user3044396

1 Answers

3
votes

This should be done with ast, and I fail to see the point in using regex to match an if statement.

I certainly don't recommend using regex here. However, it can be done with regex. The idea is to capture the spaces used to indent the if declaration, and use the backreference \1 to require that same indentation and at least one more space in the following lines.

The following regex is an example that will cover the most simple statements. For example, it will fail with multiline triple-quoted strings. You can work it from here:

pattern = re.compile(r'''
    #if statement (group 1 captures the indentation)
    ^([ \t]*)  if\b  .*  $

    #code
    (?:
        #comments with any indentation
        (?:
            \s*?
            \n  [ \t]*  [#].* 
        )*

        #Optional elif/else lines
        (?:
            \s*?
            \n\1  el(?:se|if)\b  .*  $
        )?

        #following lines with more indentation
        \s*?
        \n\1  [ \t]  .*
    )*

    \n? #last newline char
''', re.MULTILINE | re.VERBOSE)

regex101 demo ideone demo


Note: This expression can also be used to match any statement. For example, to match while loops, simply replace if with while, and remove the elif subexpression. demo