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

标签 regex date datetime date-formatting

我找到了一个匹配“神奇”日期的正则表达式(其中年份的最后两位数字与月份和日期的两位数字相同,例如 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/

相关文章:

java - 在Java中查找超过24小时的最后修改文件

angular - TypeScript:无法读取 datepipe.transform 中未定义的属性 'transform'

javascript - 正则表达式或其他方式转换为 JavaScript 中的驼峰式大小写

javascript - 在 JavaScript 中使用正则表达式来检查模式重用(例如,在字符串中声明两次的相同字符序列)

java - 如果Java中的字符串以特殊字符开头,如何将第一个字母大写?

javascript - 将 JavaScript new Date() 转换为 php DateTime()

javascript - 使用 Javascript 将日期字符串格式化为所需格式

php - 如何使用正则表达式在最后一次模式出现后捕获字符?

javascript客户端日期格式

php - 将日期转换为 unixtime php