日期格式 dd.MM.yyyy 的正则表达式模式

本文关键字:正则表达式 模式 yyyy MM 格式 dd 日期 | 更新日期: 2023-09-27 17:55:12

是否有任何正则表达式模式存储,我可以在其中找到像dd.MM.yyyy这样的模式,或者你可以帮我解决这个问题?

我正在使用带有数据注释的数据验证:

[RegularExpression(@"pattern", ErrorMessage = "incorrect date format")]
public string MyDate { get; set; }

日期格式 dd.MM.yyyy 的正则表达式模式

不检查短月和闰年的模式:

string pattern = @"(0[1-9]|[12][0-9]|3[01])'.(0[1-9]|1[012])'.(19|20)'d'd"

根据 ECMAScript 规范,快速答案可能是

^('d{2}).'d{2}.('d{4})$

你可以使用这样的东西:

'd{1,2}''.'d{1,2}''.(19'd'd|20'd'd)

您可以随时尝试使用正则表达式工具,例如"RegExBuddy"或"Rad Software Regular Expression Designer"。

但是你想要的正则表达式可能是这样的:

'd{2}.'d{2}.'d{4}?
// Each month has a different number of days.
// More over, we have different number of days in February which depends on whether
// the year is a leap year. Here is how to solve this problem:
// 1) if the first digit is even, the second digit must be 0, 4, or 8
// 2) if the first digit is odd, the second digit must be 2 or 6
var pattern = "^([02468][048]|[13579][26])$";
// Deal with months with 31 days
var d1 = @"(3[01]|[012]'d|'d)'.(0?[13578]|10|12)'.'d{4}";
// Deak with months with 30 days
var d2 = @"(30|[012]'d|'d)'.(0?[469]|11)'.'d{4}";
// This portion deals with February 29 in leap years
var d3 = @"29'.(0?2)'.'d{2}([02468][048]|[13579][26])";
// Deal with other days in February
var d4 = @"(2[0-8]|[01]'d|'d)'.(0?2)'.'d{4}";
// Full pattern
var date_pattern = $"^({d1}|{d2}|{d3}|{d4})$";
var dates = new[]
{
    "11.12.2001",
    "15.99.2021",
    "14.01.2010",
    "29.02.2020", //leap year
    "29.02.2019", //not a leap year
    "28.02.2019"
};
foreach (var date in dates)
{
    WriteLine($"Date: {date}, Is match: {Regex.IsMatch(date, date_pattern)}");
}
// Output:
// Date: 11.12.2001, Is match: True
// Date: 15.99.2021, Is match: False
// Date: 14.01.2010, Is match: True
// Date: 29.02.2020, Is match: True
// Date: 29.02.2019, Is match: False
// Date: 28.02.2019, Is match: True