我找到了一个匹配“神奇”日期的正则表达式(其中年份的最后两位数字与月份和日期的两位数字相同,例如 2008-08-08):
\b[0-9][0-9]\([0-9][0-9])-\1-\1\b
...但我无法理解。它是如何工作的?
最佳答案
这是相同的正则表达式,带有详细的注释:
\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]
匹配s,然后紧随其后的“08”与接下来的两个 [0-9]
匹配s(位于括号中,以便将“08”保存到变量 \1
中)。
然后匹配一个连字符,然后08
再次(因为它之前存储在变量 \1
中),然后是另一个连字符,然后是 08
(如 \1
)再次。
关于regex - 使用正则表达式匹配 "magical"日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27928765/