匹配“魔法”日期与正则表达式

时间:2015-01-13 18:15:12

标签: regex date datetime date-formatting

我找到了一个符合“神奇”日期的正则表达式(其中年份的最后两位数字与月份和日期的两位数相同,例如2008-08-08):

\b[0-9][0-9]\([0-9][0-9])-\1-\1\b

......但我无法理解。它是如何工作的?

2 个答案:

答案 0 :(得分:4)

这是相同的正则表达式,用评论写得很详细:

\b            # The beginning or end of a word.
[0-9]         # Any one of the characters '0'-'9'.
[0-9]         # Any one of the characters '0'-'9'.
(             # Save everything from here to the matching ')' in a variable '\1'.
    [0-9]     # Any one of the characters '0'-'9'.
    [0-9]     # Any one of the characters '0'-'9'.
)             # 
-             # The literal character '-'
\1            # Whatever was saved earlier, between the parentheses.
-             # The literal character '-'
\1            # Whatever was saved earlier, between the parentheses.
\b            # The beginning or end of a word.

在'2008-08-08'的情况下,'20'与前两个[0-9]相匹配,然后紧接其后的'08'与下两个匹配{{1 s(在括号中,以便'08'保存到变量[0-9])。

然后匹配一个hypen,然后再次\1(因为它先前存储在变量08中),然后是另一个连字符,然后是\1(作为08)试。

答案 1 :(得分:1)

您可以使用正则表达式:

\b[0-9]{2}([0-9]{2})-\1-\1\b

在捕获的组#1中捕获最后2位数字,然后在捕获的组中进行反向引用,即稍后在月份和日期部分使用\1

RegEx Demo