正则表达式匹配有效日期 [英] Regular Expression to match valid dates
本文介绍了正则表达式匹配有效日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个验证日期的正则表达式。正则表达式需要匹配以下
- M / D / YYYY
- MM / DD / YYYY
- 单位数字可以以前导零开始(例如:03/12/2008)
- 单位数可以从零开始例如:3/02/2008)
- 不能包含2月30日或2月31日(例如:2008年2月31日)
到目前为止,我有
^(([1-9] | 1 [012]) [ - /。]([1-9] | [12] [0-9] | 3 [01])[ - /。](19 | 20)\d\d)|((1 [012] | | | | | | | | | | | | | | | | | | | |((1 [012] | 0 [1-9])[ - /。](3 [01] | 2\d | 1\d | 0 [1-9])[ - /。](19 | 20)\d\\ \\ d)$
这个匹配正确除了它还包括2/30/2008& 2/31/2008。
有没有人有更好的建议?
编辑: strong>我在RegExLib上发现了答案
$ b $ ([(1- [])(((1 [02]))[(1 [02])) |([0-2] [0-9])|(3 [01])))|(((0 [469])|([469])|(11))[\ / 1-([1-9])|([0-2] [0-9])|(30)))|((2 | 02)[\ /](([1-9])|([0-2 ] [0-9]))))[\ /] \d {4} $ | ^ \d {4} $
它匹配MM / DD / YYYY格式之后的所有有效月份。
感谢大家的帮助。
解决方案
这不正确的使用正则表达式。你最好使用
[0-9] {2} / [0-9] {2} / [ 0-9] {4}
然后检查更高级别语言的范围。 >
I'm trying to write a regular expression that validates a date. The regex needs to match the following
- M/D/YYYY
- MM/DD/YYYY
- Single digit months can start with a leading zero (eg: 03/12/2008)
- Single digit days can start with a leading zero (eg: 3/02/2008)
- CANNOT include February 30 or February 31 (eg: 2/31/2008)
So far I have
^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d)|((1[012]|0[1-9])(3[01]|2\d|1\d|0[1-9])(19|20)\d\d)|((1[012]|0[1-9])[-/.](3[01]|2\d|1\d|0[1-9])[-/.](19|20)\d\d)$
This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008.
Does anyone have a better suggestion?
Edit: 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}$
It matches all valid months that follow the MM/DD/YYYY format.
Thanks everyone for the help.
解决方案
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屋!
查看全文