日期匹配正则表达式

时间:2015-09-03 14:30:30

标签: python regex

我正在尝试在以下数据集中匹配年份:

2014-15 blah
14-15 blah
2015 blah
12/1/2015
2015/25/1
blah 2015-2016
blah-2008
blah 14-15

它应匹配所有4位数或2位数年份。每年的时间是2位数,它将是字符串中唯一的数字。

这是我到目前为止的正则表达式(\d{2,4})(?:\s|-|/|$),但问题是如果它是两位数的日/月匹配日/月。如果它采用day/month/yearyear/month/day的形式,则年份将始终为完整的四位数。

这需要使用Python的re模块。

2 个答案:

答案 0 :(得分:1)

如果我正确理解了您的要求,您可以使用这个基于前瞻性的正则表达式:

\b(?:\d{4}(?=/|$)|\d{2}\d{2}?(?=[\s-]|$))

RegEx分手:

\b                      # word boundary
(?:                     # start non-capturing group
\d{4}(?=/|$)            # match 4 digit that should be followed by a / or end of string
|                       # alternation
\d{2}\d{2}?(?=[\s-]|$)  # match 2 or 4 digits that are followed by a space or -
                        # or end of input
)                       # end non-capturing group

RegEx Demo

答案 1 :(得分:1)

您可以使用

\b\d{4}\b|(?<!\b\d{4}/)(?<!\b\d{2}/)\b\d{2}\b(?!(?:/\d{1,2})?/\d{4}\b)

请参阅demo

正则表达式将匹配2个替代方案:

  • \b\d{4}\b - 作为整个单词的任何4位数序列
  • (?<!\b\d{4}/)(?<!\b\d{2}/)\b\d{2}\b(?!(?:/\d{1,2})?/\d{4}\b) - 作为整个单词的任意2位数字,前面没有4位或2位数字,并且后面没有2位/ 4位整字。