简体   繁体   English

用正则表达式匹配“神奇”的日期

[英]Matching “magical” dates with regex

I've found a regular expression which matches "magical" dates (in which the last two digits of the year are the same as the two digits of the month and day, for example 2008-08-08): 我找到了一个匹配“不可思议”日期的正则表达式(其中年份的最后两位数字与月份和日期的两位数字相同,例如2008-08-08):

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

... but I can't understand it. ...但是我听不懂。 How does it work? 它是如何工作的?

Here's the same regex, written verbosely with comments: 这是相同的正则表达式,详细写有注释:

\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.

In the case of '2008-08-08', the '20' gets matched by the first two [0-9] s, and then the '08' immediately after that gets matched by the next two [0-9] s (which are in parentheses, so that '08' gets saved to the variable \\1 ). 在'2008-08-08'的情况下,'20'与前两个[0-9] s匹配,然后紧随其后的'08'与后两个[0-9] s匹配。 (在括号中,因此'08'被保存到变量\\1 )。

Then a hypen is matched, then 08 again (because it was stored in the variable \\1 earlier), then another hyphen, then 08 (as \\1 ) again. 然后匹配一个连字符,然后再匹配08 (因为它之前存储在变量\\1 ),然后是另一个连字符,然后又匹配了08 (作为\\1 )。

You can use regex: 您可以使用正则表达式:

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

Last 2 digits are captured in captured group #1 and then back-reference of captured group ie \\1 is used in month and date part later. 在捕获的组#1中捕获最后2位数字,然后在捕获的组的后向引用中使用\\1\\1

RegEx Demo 正则演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM