【问题标题】:Date regex python日期正则表达式 python
【发布时间】:2015-06-20 19:46:40
【问题描述】:

我正在尝试匹配日期格式为(月 dd,yyyy)的字符串中的日期。当我在下面使用我的正则表达式模式时,我对看到的内容感到困惑。它只匹配以日期开头的字符串。我错过了什么?

 >>> p = re.compile('[A-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}')
 >>> s = "xyz Dec 31, 2013 - Jan 4, 2014"
 >>> print p.match(s).start()
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 AttributeError: 'NoneType' object has no attribute 'start'

 >>> s = "Dec 31, 2013 - Jan 4, 2014"
 >>> print p.match(s).start()
 0 #Correct

【问题讨论】:

    标签: python regex date


    【解决方案1】:

    使用re.findall 而不是re.match,它会返回给你所有匹配的列表:

    >>> s = "Dec 31, 2013 - Jan 4, 2014"
    >>> r = re.findall(r'[A-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}',s)
    >>> r
    ['Dec 31, 2013', 'Jan 4, 2014']
    >>>
    >>> s = 'xyz Dec 31, 2013 - Jan 4, 2014'
    >>> r = re.findall(r'[A-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}',s)
    >>> r
    ['Dec 31, 2013', 'Jan 4, 2014']
    

    来自Python docs

    re.match(pattern, string, flags=0) 如果零个或多个字符在 字符串开头 匹配正则表达式模式,返回一个 对应的 MatchObject 实例

    另一方面:

    findall() 匹配所有出现的模式,而不仅仅是第一个 就像 search() 一样。

    【讨论】:

      【解决方案2】:

      使用搜索方法而不是匹配。 Match 比较整个字符串,但搜索会找到匹配的部分。

      【讨论】:

        【解决方案3】:
        p = re.compile(r'.*?[A-Za-z]{3}\s{1,}\d{1,2}[,]\s{1,}\d{4}')
        

        match 匹配来自 start 的字符串。如果 start 不相同,它将失败。在第一个示例中,xyz 将被 [A-Za-z]{3} 使用,但字符串的其余部分将不匹配。

        您可以直接将您的正则表达式与re.findall 一起使用并获得结果,而无需关心匹配的位置。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-20
          • 1970-01-01
          • 2011-06-10
          • 1970-01-01
          • 1970-01-01
          • 2017-05-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多