使用可选时间验证 dd/mm/yyyy 的正则表达式 [英] Regex for validating dd/mm/yyyy with optional time

查看:53
本文介绍了使用可选时间验证 dd/mm/yyyy 的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个正则表达式来验证日期是否采用以下格式之一:

I want a regex which will validate that dates are in one of the following formats:

  • 日/月/年
  • dd/MM/yyyy hh:mm
  • dd/MM/yyyy hh:mm:ss

到目前为止我有

^([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2]\d{3}((\s([0-1]\d|[2][0-3])\:[0-5]\d\((:[0-5]\d)?)?)$

我一直在在线正则表达式测试器中尝试.当我尝试 21/05/2014 但不是 21/05/2014 15:5421/05/2014 15:54:12<时,输入匹配/代码>

which I have been trying in an online regex tester. The input matches when I try 21/05/2014 but not 21/05/2014 15:54 or 21/05/2014 15:54:12

可能是放错地方了?错误,但以我有限的正则表达式技能,它在我看来是正确的.

It's probably a misplaced ? error, but with my limited regex skills it looks correct to me.

请注意,我不想对闰年和月份中的天数等事情过于挑剔.[01-31]/[01-12]/[1000-2999] 日期部分没问题.

Note that I am not looking to be overly fussy about things like leap years and days in the month. [01-31]/[01-12]/[1000-2999] is fine for the date part.

推荐答案

在你的时间表达式中,你试图匹配一个文字左括号:

In your expression for time, you are trying to match a literal open parenthesis:

((\s([0-1]\d|[2][0-3])\:[0-5]\d\((:[0-5]\d)?)?)
                               ^^

如果你删除它,你应该很好.但是,我稍微清理了一些比赛组..所以 1 是日,2 是月,3 是年,4 是小时,5 是分钟,6 是秒:

If you remove that, you should be good. However, I cleaned up some of these match groups a bit..so 1 is day, 2 is month, 3 is year, 4 is hour, 5 is minute, 6 is second:

^([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/([1-2]\d{3})(?:(?:\s([0-1]\d|[2][0-3])\:([0-5]\d)(?::([0-5]\d))?)?)$

演示

但是,对于如此复杂的表达式,可能值得使用 x 修饰符并添加空格 &用 (?# ... ) 注释.

However, with an expression this complicated, it may be worth using the x modifier and adding whitespace & comments with (?# ... ).

最后,我可以建议一些更简单的,例如:

Finally, may I suggest something much simpler like:

^\d{2}\/\d{2}\/\d{4}\s*(?:\d{2}:\d{2}(?::\d{2})?)?$

这更容易阅读/修改/调试,并且仍然会匹配同一组数字.您可以使用您的语言(PHP、Java、Javascript、Python 等)库来尝试创建一个 DateTime 类.如果它失败了,那么你就知道它是一个无效的日期.这也会更加准确,因为您的表达式仍将匹配不是一天的 30/02/2014.

This is easier to read/modify/debug, and will still match the same group of numbers. Than you can use your language's (PHP, Java, Javascript, Python, etc) libraries to attempt to create a DateTime class. If it fails, then you know its an invalid date. This will be even more accurate as well, since your expression will still match 30/02/2014 which is not a day.

这篇关于使用可选时间验证 dd/mm/yyyy 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆