【问题标题】:Clean Python Regular Expressions清理 Python 正则表达式
【发布时间】:2010-10-31 19:49:18
【问题描述】:

有没有一种更简洁的方法可以在 python 中编写长正则表达式模式?我在某处看到了这种方法,但 python 中的正则表达式不允许列表。

patterns = [
    re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'),
    re.compile(r'\n+|\s{2}')
]

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    您可以使用详细模式来编写更具可读性的正则表达式。在这种模式下:

    • 模式中的空格将被忽略,除非在字符类中或前面有未转义的反斜杠。
    • 当行包含字符类中的“#”或前面没有未转义的反斜杠时,从最左边的“#”到行尾的所有字符都将被忽略。

    以下两个语句是等价的:

    a = re.compile(r"""\d +  # the integral part
                       \.    # the decimal point
                       \d *  # some fractional digits""", re.X)
    
    b = re.compile(r"\d+\.\d*")
    

    (取自verbose mode的文档)

    【讨论】:

    • 可能值得指出的是“re.X”表示详细模式,相当于写“re.VERBOSE”。
    【解决方案2】:

    虽然@Ayman 关于re.VERBOSE 的建议是一个更好的主意,但如果你想要的只是你所展示的,那就去做吧:

    patterns = re.compile(
            r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'
            r'\n+|\s{2}'
    )
    

    而 Python 的相邻字符串文字的自动连接(很像 C 语言,顺便说一句)将完成剩下的工作;-)。

    【讨论】:

    • 这将是 Python 的自动连接结合 Python 的括号和括号之间的自动行连接。
    【解决方案3】:

    您可以在正则表达式中使用 cmets,这使它们更具可读性。以http://gnosis.cx/publish/programming/regular_expressions.html为例:

    /               # identify URLs within a text file
              [^="] # do not match URLs in IMG tags like:
                    # <img src="http://mysite.com/mypic.png">
    http|ftp|gopher # make sure we find a resource type
              :\/\/ # ...needs to be followed by colon-slash-slash
          [^ \n\r]+ # stuff other than space, newline, tab is in URL
        (?=[\s\.,]) # assert: followed by whitespace/period/comma 
    /
    

    【讨论】:

    • ...只要按照 Ayman 的建议使用 re.VERBOSE 编译它们。
    猜你喜欢
    • 1970-01-01
    • 2010-11-27
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多