匹配有效日期的正则表达式 [英] Regular Expression to match valid dates
本文介绍了匹配有效日期的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个验证日期的正则表达式.正则表达式需要匹配以下内容
I'm trying to write a regular expression that validates a date. The regex needs to match the following
- 月/日/年年
- MM/DD/YYYY
- 个位数月份可以以前导零开头(例如:03/12/2008)
- 个位数的天数可以以前导零开头(例如:3/02/2008)
- 不能包括 2 月 30 日或 2 月 31 日(例如:2/31/2008)
到目前为止我有
^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)dd)|((1[012]|0[1-9])(3[01]|2d|1d|0[1-9])(19|20)dd)|((1[012]|0[1-9])[-/.](3[01]|2d|1d|0[1-9])[-/.](19|20)dd)$
这正确匹配除了它仍然包括 2/30/2008 &2008 年 2 月 31 日.
This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008.
有人有更好的建议吗?
我在 RegExLib 上找到了答案
I found the answer on RegExLib
^((((0[13578])|([13578])|(1[02]))[/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[/](([1-9])|([0-2][0-9])|(30)))|((2|02)[/](([1-9])|([0-2][0-9]))))[/]d{4}$|^d{4}$
它匹配所有遵循 MM/DD/YYYY 格式的有效月份.
It matches all valid months that follow the MM/DD/YYYY format.
感谢大家的帮助.
推荐答案
这不是正则表达式的适当用法.你最好使用
This is not an appropriate use of regular expressions. You'd be better off using
[0-9]{2}/[0-9]{2}/[0-9]{4}
然后用高级语言检查范围.
and then checking ranges in a higher-level language.
这篇关于匹配有效日期的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文