【问题标题】:Python Cannot Parse Date with RegexPython 无法使用正则表达式解析日期
【发布时间】:2015-08-13 20:11:31
【问题描述】:

我有一个程序,用户可以在其中输入字符串并在字符串中包含日期。我正在使用 RegEx 匹配 \d+\/\d+\/\d+ 从字符串中提取日期,但由于某种原因,在我的测试用例中,只有最后一个条目能够工作

import datetime
import re
dateList = []
dates = ["Foo (8/15/15) Bar", "(8/15/15)", "8/15/15"]
reg = re.compile('(\d+\/\d+\/\d+)')
for date in dates:
    matching = reg.match(date)
    if matching is not None:
        print date, matching.group(1)
    else:
        print date, "is not valid date"

返回

Foo (8/15/15) Bar is not valid date
(8/15/15) is not valid date
8/15/15 8/15/15

我的 RegEx 有问题吗?我用 RegEx101.com 对其进行了测试,它似乎工作正常

【问题讨论】:

标签: python regex


【解决方案1】:

如果您正在寻找正则表达式的部分匹配项,请使用搜索:

import datetime
import re
dateList = []
dates = ["Foo (8/15/15) Bar", "(8/15/15)", "8/15/15"]
reg = re.compile('([0-9]+/[0-9]+/[0-9]+)')
for date in dates:
    matching = reg.search(date)  # <- .search instead of .match
    if matching is not None:
        print( date, matching.group(1) )
    else:
        print( date, "is not valid date" )

【讨论】:

  • 请注意\d 不是 Unicode 模式下[0-9] 的别名,这是默认设置。有关更多上下文,请参阅我的答案。
【解决方案2】:

您正在寻找search(),而不是match()

date_re = re.compile('([0-9]{2})/([0-9]{2})/([0-9]{2})')
e = date_re.match('foo 01/02/13')
# e is None
e = date_re.search('foo 01/02/13')
# e.groups() == ('01', '02', '13')

不要在您期望 ASCII 0-9 数字的地方使用\d,因为there are many strange things\d 的Unicode 版本匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多