正则表达式匹配日期

我想用mm / dd / yy或mm / dd / yyyy格式匹配日期,但它不应该选择23/09/2010,其中月份是23,这是无效的,也不是某些无效的日期,例如00/12/2020或12/00 / 2011。



繁星点点滴滴
浏览 962回答 3
3回答

SMILET

您最好对/进行拆分,然后测试所有单个部分。但是,如果您真的想使用正则表达式,可以尝试以下一种:#\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我已经解释了第一部分,其余部分留作练习。此匹配一个无效日期:02/29/1900,但对于01/01/1900到12/31/2099之间的任何其他日期都是正确的

心有法竹

您可以使用regexp做的最好的事情就是验证格式,例如:[0-1][0-9]/[0-3][0-9]/[0-9]{2}(?:[0-9]{2})?如果没有某种日期字典,则无法可靠地完成任何其他工作。例如,日期的有效性取决于是否为a年。
打开App,查看更多内容
随时随地看视频慕课网APP