【问题标题】:Why doesn't this Regex match any of the dates?为什么这个正则表达式不匹配任何日期?
【发布时间】:2020-12-20 04:36:01
【问题描述】:

我正在尝试使用正则表达式将数据框中的日期与 500 个条目匹配:

日期可以以下列格式显示:

04/20/2009; 04/20/09; 4/20/09; 4/3/09
Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;
20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009
Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009
Feb 2009; Sep 2009; Oct 2010
6/2008; 12/2009
2009; 2010

dates[dates[0].str.contains(r'(?P<year>\d?\d?\d\d)')].shape

返回一个shape(500,1)的元组

但是

dates[dates[0].str.contains(r'((?P\<day\>(\d?\d)?(\s|-|/|th|st|nd)?)??P\<year\>(\d?\d?\d\d))')].shape

返回一个shape(0,1)的元组,但是天组是可选的,所以它不应该仍然匹配年份组。

【问题讨论】:

    标签: python regex pandas re


    【解决方案1】:

    好的,我明白了。

    正确的正则表达式模式是: r'((?P(\d?\d)?(\s|-|/|th|st|nd)?)?(?P\d?\d?\d\d ))'

    年份组的括号位置错误。

    【讨论】:

    • (\d{4}|\d{2})) 如果您想要 4 或 2 位数字结尾。 3 位数字将匹配 rn。
    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多