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.
-3
votes
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)
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
astinstead? - roippiast- dawga block is exited when the indentation goes downNot always. Comments can be any indentation - dawg