正则表达式匹配日期 [英] Regex to match Date
问题描述
我想匹配格式为 mm/dd/yy 或 mm/dd/yyyy 的日期,但它不应该选择 23/09/2010,其中月份为 23 是无效的,也不是一些无效的日期,例如 00/12/2020 或 12/00/2011.
I want to match dates with format mm/dd/yy or mm/dd/yyyy but it should not pick 23/09/2010 where month is 23 which is invalid nor some invalid date like 00/12/2020 or 12/00/2011.
推荐答案
您最好对/进行拆分并测试所有单独的部分.但如果你真的想使用正则表达式,你可以试试这个:
You'd better do a split on / and test all individual parts. But if you really want to use a regex you can try this one :
#\A(?:(?:(?:(?:0?[13578])|(1[02]))/31/(19|20)?\d\d)|(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)|(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))|(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d))\Z#
说明:
\A # start of string
(?: # group without capture
# that match 31st of month 1,3,5,7,8,10,12
(?: # group without capture
(?: # group without capture
(?: # group without capture
0? # number 0 optionnal
[13578] # one digit either 1,3,5,7 or 8
) # end group
| # alternative
(1[02]) # 1 followed by 0 or 2
) # end group
/ # slash
31 # number 31
/ # slash
(19|20)? #numbers 19 or 20 optionnal
\d\d # 2 digits from 00 to 99
) # end group
|
(?:(?:(?:0?[13-9])|(?:1[0-2]))/(?:29|30)/(?:19|20)?\d\d)
|
(?:0?2/29/(?:19|20)(?:(?:[02468][048])|(?:[13579][26])))
|
(?:(?:(?:0?[1-9])|(?:1[0-2]))/(?:(?:0?[1-9])|(?:1\d)|(?:2[0-8]))/(?:19|20)?\d\d)
)
\Z
我已经解释了第一部分,剩下的作为练习.
I've explained the first part, leaving the rest as an exercise.
此匹配一个无效日期:02/29/1900 但对于 01/01/1900 和 12/31/2099 之间的任何其他日期都是正确的
This match one invalid date : 02/29/1900 but is correct for any other dates between 01/01/1900 and 12/31/2099
这篇关于正则表达式匹配日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!