Regex Matching Everything Within a Python If Statement

后端 未结 1 983
陌清茗
陌清茗 2020-12-22 14:07

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 \'

相关标签:
1条回答
  • 2020-12-22 14:37

    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

    0 讨论(0)
提交回复
热议问题