使用正则表达式匹配 "magical" 个日期

Matching "magical" dates with regex

我找到了一个匹配"magical"日期的正则表达式(其中年份的最后两位数与月份和日期的两位数相同,例如2008-08-08 ):

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

...但是我看不懂。它是如何工作的?

您可以使用正则表达式:

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

最后 2 位数字在捕获组 #1 中被捕获,然后是捕获组的反向引用,即 用于稍后的月份和日期部分。

RegEx Demo

这里是同一个正则表达式,写得很冗长并带有注释:

\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 ''.
    [0-9]     # Any one of the characters '0'-'9'.
    [0-9]     # Any one of the characters '0'-'9'.
)             # 
-             # The literal character '-'
            # Whatever was saved earlier, between the parentheses.
-             # The literal character '-'
            # Whatever was saved earlier, between the parentheses.
\b            # The beginning or end of a word.

在“2008-08-08”的情况下,“20”与前两个 [0-9] 匹配,紧随其后的“08”与下两个 [0-9]s(在括号中,以便将“08”保存到变量 </code>)。</p> <p>然后匹配一个连字符,然后再次匹配<code>08(因为它之前存储在变量</code>中),然后是另一个连字符,然后是<code>08(因为) 再一次。