正则表达式匹配 Python If 语句中的所有内容 [英] Regex Matching Everything Within a Python If Statement

查看:97
本文介绍了正则表达式匹配 Python If 语句中的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个正则表达式,该表达式将匹配 python if 语句等中的所有内容.到目前为止,我的开头匹配为 ':[\n][\t]' ,但我无法找出正则表达式来检测 if 的关闭> python 中的语句.到目前为止,我能想到的最好的方法是 [\n][^\t] 因为我知道当换行符后面没有制表符时会退出块.

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.

推荐答案

这应该通过 ast,我看不出使用正则表达式匹配 if 语句的意义.

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

我当然不建议在这里使用正则表达式.但是,它可以使用正则表达式完成.这个想法是捕获用于缩进 if 声明的空格,并使用反向引用 \1 来要求相同的缩进和在以下行中至少多一个空格.

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 演示 ideone 演示

注意:这个表达式也可以用来匹配任何语句.例如,要匹配 while 循环,只需将 if 替换为 while,并删除 elif 子表达式.演示

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

这篇关于正则表达式匹配 Python If 语句中的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆