以下正则表达式有何作用?
^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$
特别是\1
部分的目的是什么?
答案 0 :(得分:4)
你应该看看a tutorial。那里几乎没有任何进展(除了你指出的那个\1
):
^ # the start of the string
\d # a digit
{1,2} # 1 or 2 of those
( # start the first subpattern, which can later be referred to with \1
\- # a literal hyphen (there is no need for escaping, but it doesn't hurt)
| # or
\/ # a literal slash
| # or
\. # a literal period
) # end of subpattern
\d{1,2} # one or two more digits
\1 # the exact same thing that was matched in the first subpattern. this
# is called a backreference
\d{4} # 4 digits
$ # the end of the string
即。这断言输入字符串恰好包含格式ddmmyyyy
(或者也可能是mmddyyyy
)的一个日期,不多也不少,包含可能的分隔符.
,-
或/
(以及一致的分隔符用法)。请注意,它无法确保正确的日期。月份和日期可以是00
到99
。
注意 \d
的确切含义取决于您正在使用的正则表达式引擎和文化。 通常表示[0-9]
(任何ASCII数字)。但是,例如在.NET中,它也可以表示“任何表示数字的Unicode字符”。
答案 1 :(得分:3)
^
字符串开头\d{1,2}
匹配1或2位数字(0-9)(\-|\/|\.)
匹配“ - ” OR “/” OR “。”\d{1,2}
再次匹配1或2位数字(0-9)\1
是反向引用。匹配第3组中该组捕获的同一角色的另一个实例\d{4}
匹配4位数字$
字符串结尾这将匹配以下格式的日期。请注意,dd
,mm
和yyyy
范围未被检查,因此日期可能仍然无效。
d-m-yyyy
d/m/yyyy
d.m.yyyy
d
& m
可以是1 或 2位数。
答案 2 :(得分:1)
匹配:
\1
是对第一组匹配的值的反向引用,即(\-|\/|\.)
。
例如:
2-14-2003
99.99.9999
1/2/0001