【问题标题】:How to clean up regular expression如何清理正则表达式
【发布时间】:2014-01-31 22:14:16
【问题描述】:

我的 python 代码中有以下正则表达式,它真的很长。由于 python 是一种以空格分隔的语言,我该如何清理它?

matches = re.findall("((?:jan(?:(?:.)?|(?:uary)?)|feb(?:(?:.)?|(?:ruary)?)|mar(?:(?:.)?|(?:ch)?)|apr(?:(?:.)?|(?:il)?)|may|jun(?:(?:.)?|(?:e)?)|jul(?:(?:.)?|(?:y)?)|aug(?:(?:.)?|(?:gust)?)|sep(?:(?:.)?|(?:ept(?:(?:.)?))?|(?:tember)?)|oct(?:(?:.)?|(?:ober)?)|nov(?:(?:.)?|(?:ember)?)|dec(?:(?:.)?|(?:ember)?)) (?:[12][0-9]|[1-9]))",fileText,re.IGNORECASE)

任何帮助将不胜感激。

【问题讨论】:

  • 请您解释一下该模式的逻辑。这种模式的正则表达式应该捕捉到什么?

标签: python regex python-2.7


【解决方案1】:

您可以使用re.VERBOSE 标志将正则表达式分成多行。

请注意,要使用多个标志,您必须使用按位或运算符:

flags = re.IGNORECASE | re.VERBOSE

【讨论】:

    【解决方案2】:

    我更喜欢这样编写复杂的正则表达式:

    r"""(?x)
        ....
    """
    

    在哪里

    • r 开始一个原始文字,因此斜杠只转义一次
    • """ 开始一个多行文字
    • (?x) 打开扩展(详细)模式:忽略空格,允许 cmets

    你的例子:

    date = r"""(?xi)
    
        (?:  # this is a comment
              jan (?: \.|uary)?
            | feb (?: \.|ruary)?
            | mar (?: \.|ch)?
            | apr (?: \.|il)?
    
            etc
        )
        (?: # well, how about 30, 31?
            [12][0-9] | [1-9]
        )
    
    """
    

    像(?xi) 这样的内联标志比re.XXX 更具可读性,因为它们绑定到表达式本身,也就是它们所属的地方。

    【讨论】:

      【解决方案3】:

      这是你想要的吗?

      import re
      
      regx = re.compile("("
                        "(?:"
                        "jan(?:\.|uary)"
                        "|"
                        "feb(?:\.|ruary)"
                        "|"
                        "mar(?:\.|ch)"
                        "|"
                        "apr(?:\.|il)"
                        "|"
                        "may"
                        "|"
                        "ju(?:n[.e]|l[.y])"
                        "|"
                        "aug(?:\.|ust)"
                        "|"
                        "sep(?:\.|tember)"
                        "|"
                        "oct(?:\.|ober)"
                        "|"
                        "(?:nov|dec)(?:\.|ember)"
                        ")"
                        " (?:[12][0-9]|[1-9]|3[01])"
                        ")",
                        re.IGNORECASE)
      
      
      s = "ght july 24 tiren august 23 hyu jan. 11"
      
      print regx.findall(s)
      

      结果

      ['july 24', 'august 23', 'jan. 11']
      

      括号之间的点失去了它的特殊含义。

      【讨论】:

        猜你喜欢
        • 2010-10-31
        • 2010-11-27
        • 2010-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多