正则表达式用于验证日期,包括闰年2月。 [英] Regex expression to validate date including february in leap years.

查看:142
本文介绍了正则表达式用于验证日期,包括闰年2月。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式,它应该能够在闰年中验证2月,即如果用户在闰年中提供28-feb-2016,我将无法提交页面。





谢谢



我的尝试:



这就是我的尝试





^(([1-9]) |([0] [1-9])|([1-2] [0-9])|([3] [0-1]))\-(一月| 2月| 3月|四月|五月| Jun | Jul | Aug | Sep | Oct | Nov | Dec)\-\d {4} $

解决方案


< blockquote>

引用:

我需要一个正则表达式,它应该能够在闰年验证2月,即如果我不能提交页面用户在闰年时提供28-feb-2016。



在这种情况下,您还需要检查31天的月份并拒绝'31 Jun'。我上次检查时,'28 Feb'每年都是正确的,跳跃与否。

即使可能,你想用RegEx做什么也是一种虐待。



我会使用RegEx检查日期格式大致为'99 aaa 9999',然后我知道格式是正确的,然后是一段JS代码。



使用RegEx检查深层详细信息的问题在于,当您引入这些详细信息时,RegEx将退化。问题是你不能在RegEx中包含微积分,因此你必须描述在一般情况下不适合的所有可能性。

一旦你知道输入匹配一般格式的a日期,一点点简单的JS代码可以检查年份是否跳跃(年份%4 == 0)



只是一些有趣的链接来帮助建立和调试RegEx。

以下是RegEx文档的链接:

perlre - perldoc.perl.org [ ^ ]

以下是帮助构建RegEx并调试它们的工具的链接:

.NET Regex Tester - Regex Storm [ ^ ]

快速正则表达式工具 [ ^ ]

这个显示RegEx是一个很好的图表,它非常有助于理解RegEx的作用:

Debuggex:在线可视正则表达式测试程序。 JavaScript,Python和PCRE。 [ ^ ]


i need a regex expression which should be able to validate february in leap years i.e i should not be able to submit the page if the user gives 28-feb-2016 for a leap year.


Thanks

What I have tried:

This is what i have tried


^(([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$

解决方案


Quote:

i need a regex expression which should be able to validate february in leap years i.e i should not be able to submit the page if the user gives 28-feb-2016 for a leap year.


In this case, you also need to check for months with 31 days and reject '31 Jun'. Last time I checked, '28 Feb' was correct every year, leap or not.
Even if possible, what you want to do with RegEx is kind of abuse.

I would use RegEx to check date format roughly '99 aaa 9999', and then a piece of JS code once I know the format is correct.

The problem with checking deep details with RegEx, is that the RegEx will degenerate as you introduce those details. The problem is that you can't include calculus in the RegEx, and thus you have to describe every possibility that don't fit in general case.
Once you know the input match the general format of a date, a little 'simple) piece of JS code can check if year is leap or not (year % 4 == 0)

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]


这篇关于正则表达式用于验证日期,包括闰年2月。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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