我需要用正则表达式验证格式为dd/mm/yyyy的日期字符串。

这个正则表达式验证dd/mm/yyyy,但不验证像31/02/4500这样的无效日期:

^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$

什么是有效的正则表达式来验证支持闰年的dd/mm/yyyy格式?


当前回答

这是一个正则表达式,用于匹配日期格式的字符串,YYYY-MM-DD,使用不同类型的分隔符。它甚至在句子中匹配字符串,并且日期以st, nd和其他结尾。

举个例子,它与下面句子中的日期相匹配:

"Her birthday is 2022 February 23rd; I will present here a gift."

"Her birthday is 2022 Feb 23rd; I will present here a gift."

"Her birthday is 2022 02 23; I will present here a gift."

这是日期正则表达式:

"\b
(?<YYYY>[0-9]{4})
(?<!0000)(?<sep>[ /.,-])
(?|
    (?:(?<MM>0[13578]|1[02]|Jan(?:uary)?|Mar(?:ch)?|May|Jul(?:y)?|Aug(?:ust)?|Oct(?:ober)?|Dec(?:ember)?)\g{sep}(?<DD>0[1-9]|[12][0-9]|3[01]))|
    (?:(?<MM>0[469]|11|Apr(?:il)?|Jun(?:e)?|Sep(?:tember)?|Nov(?:ember)?)\g{sep}(?<DD>0[1-9]|[12][0-9]|30))|
    (?:(?<MM>02|Feb(?:ruary)?)\g{sep}(?<DD>0[1-9]|[12][0-9]))
)
(?:
    (?<=[023][1])st|
    (?<=[02][2])nd|
    (?<=[02][3])rd|
    (?<=(?:0[4-9])|(?:1[0-9])|20|(?:2[4-9])|30)th
)?
[,;.]?
\b"x

以我之见,对于正则表达式来说,检查闰年是没有意义的,因为可以为它编写简单、清晰和可理解的一行代码:

is_leap_year(y) = ((y%4 == 0) && (y%100 != 0)) || (y%400 == 0)

正则表达式是用来匹配字符串的,而不是用来进行计算的。最好的方法是匹配字符串,然后将捕获的MM组传递给is_leap_year函数(如果是02、Feb或February),以验证字符串。

其他回答

对于那些看到这些并感到完全困惑的人,这里是我剧本的一段摘录。不幸的是,它所做的只是匹配日期时间输入中的有效数字,31 Feb将被标记为有效,但正如许多人所说,regex真的不是做这个测试的最佳工具。

以'yyyy-MM-dd hh:mm'格式匹配日期(实际上可以按您喜欢的任何顺序匹配)

var dateerrors = false;
var yearReg = '(201[4-9]|202[0-9])';            ///< Allows a number between 2014 and 2029
var monthReg = '(0[1-9]|1[0-2])';               ///< Allows a number between 00 and 12
var dayReg = '(0[1-9]|1[0-9]|2[0-9]|3[0-1])';   ///< Allows a number between 00 and 31
var hourReg = '([0-1][0-9]|2[0-3])';            ///< Allows a number between 00 and 24
var minReg = '([0-5][0-9])';                    ///< Allows a number between 00 and 59
var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');
$('input').filter(function () {return this.id.match(/myhtml_element_with_id_\d+_datetime/);}).each(function (e) {
    if (e > 0) {
        // Don't test the first input. This will use the default
        var val = $(this).val();
        if (val && !val.trim().match(reg)) {
            dateerrors = true;
            return false;
        }
    }
});
if (dateerrors) {
    alert('You must enter a validate date in the format "yyyy-mm-dd HH:MM", e.g. 2019-12-31 19:30');
    return false;
}

上面的脚本首先构建一个正则表达式对象。然后它会找到id与某个模式匹配的所有输入,然后循环遍历这些输入。我没有测试我找到的第一个输入(if (e > 0))。

稍微解释一下:

var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');

^表示匹配的开始,而$表示匹配的结束。

return this.id.match(/myhtml_element_with_id_\d+_datetime/);

\d+表示匹配单个或连续的整数序列,因此myhtml_element_with_id_56_datetime和myhtml_element_with_id_2_datetime将匹配,但myhtml_element_with_id_5a_datetime将不匹配

试试这个。

^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$

您可以在http://www.regular-expressions.info/javascriptexample.html轻松地测试正则表达式。

请遵循以下表达方式

Regex regex = new Regex(@"(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$");

我已经根据我的要求扩展了@Ofir Luzon给出的格式dd-mmm-YYYY, dd/mmm/YYYY, dd.mmm.YYYY。任何有同样要求的人都可以参考这个

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

并在这里测试了一些测试用例https://regexr.com/39tr1。

为了更好地理解这个正则表达式,请参考下面的图片:

Edit

将其扩展为yyyy/mm/dd、yyyy-mm-dd或yyyy.mm.dd 一些测试用例https://regex101.com/r/3TZfyU/1

^(?:(?:1[6-9]|[2-9]\d)?\d{2})(?:(?:(\/|-|\.)(?:0?[13578]|1[02])\1(?:31))|(?:(\/|-|\.)(?:0?[13-9]|1[0-2])\2(?:29|30)))$|
^(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(\/|-|\.)0?2\3(?:29)$|
^(?:(?:1[6-9]|[2-9]\d)?\d{2})(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:0?[1-9]|1\d|2[0-8])$

我怀疑,在不知道用户的地区何时从儒略历切换到格里高利历的情况下,以下内容是尽可能准确的。

它接受'-','/',或者什么都不作为年,月和日之间的分隔符,不管顺序如何。

MMddyyyy:

^(((0[13-9]|1[012])[-/]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-/]?31|02[-/]?(0[1-9]|1[0-9]|2[0-8]))[-/]?[0-9]{4}|02[-/]?29[-/]?([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00))$

ddMMyyyy:

^(((0[1-9]|[12][0-9]|30)[-/]?(0[13-9]|1[012])|31[-/]?(0[13578]|1[02])|(0[1-9]|1[0-9]|2[0-8])[-/]?02)[-/]?[0-9]{4}|29[-/]?02[-/]?([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00))$

yyyyMMdd:

^([0-9]{4}[-/]?((0[13-9]|1[012])[-/]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-/]?31|02[-/]?(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00)[-/]?02[-/]?29)$

除了顺序,这些都精确到儒略历(每四年闰年),直到1700年,当公历与儒略历背离。它有两个问题:

It accepts the year 0000, which doesn't exist in many, but not all, standards. Note that ISO 8601 does accept year 0000 (equivalent to 1 BCE). It doesn't skip the 10-13 days which were lost when the Gregorian Calendar came into use. This varies by locality though. For example, the Roman Catholic Church skipped 10 days, October 5th through October 14th, 1582, but Greece (the last to switch) skipped February 16th through the 28th of 1923, 13 days, having to take into account the leap years of 1700, 1800, and 1900.

从0001年到9999年的Java日历实现已经测试了这一点,唯一的差异是上面提到的1582年的10天。