简体   繁体   English

正则表达式匹配不同格式的有效日期

[英]Regular Expression to match valid dates in different formats

I'm trying to write a regular expression that validates a date.我正在尝试编写一个验证日期的正则表达式。 The regex needs to match the following formats正则表达式需要匹配以下格式

  • MM-DD-YYYY MM-DD-YYYY
  • MM/DD/YYYY月/日/年
  • DD-MM-YYYY DD-MM-YYYY
  • DD/MM/YYYY日/月/年
  • YYYY-MM-DD YYYY-MM-DD
  • YYYY/MM/DD YYYY/MM/DD
  • YYYY-DD-MM YYYY-DD-MM
  • YYYY/DD/MM YYYY/DD/MM

and should not match formats like DD-MM/YYYY.并且不应匹配 DD-MM/YYYY 等格式。

I have tried this Regex我试过这个正则表达式

'^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\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])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$'

but I am only able to extract the dates with mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy format.但我只能提取 mm/dd/yyyy 或 mm-dd-yyyy 或 mm.dd.yyyy 格式的日期。

I also tried using this (?:\\d{2}){1,2}[-|/|.]\\d{2}-|/|.{1,2} where I am getting the dates but I am also getting the values like 5542-21-54, 99/01/2019 which does not represent the date.我也试过用这个 (?:\\d{2}){1,2}[-|/|.]\\d{2}-|/|.{1,2} 在哪里我得到日期但我还获得不代表日期的 5542-21-54、99/01/2019 等值。

Thanks, everyone for the help.谢谢大家的帮助。

If you would like to match days yo need to do this regex:如果你想匹配天你需要做这个正则表达式:

((1|2)[0-9]|3[0-1]|0?[1-9])

For the month you need:对于您需要的月份:

(0?[1-9]|1[0-2])

For the year you need (only 1900 and 2000, for the 3000 you need maybe to update your script when we will arrive in 2999):对于您需要的年份(只有 1900 和 2000,对于 3000,您可能需要在我们 2999 年到达时更新您的脚本):

((19|20)?[0-9]{2})

After you have different delimiter and date orders, so:在您有不同的分隔符和日期顺序后,因此:

((1|2)[0-9]|3[0-1]|0?[1-9])\/(0?[1-9]|1[0-2])\/((19|20)?[0-9]{2}) # for DD/MM/YYYY
((1|2)[0-9]|3[0-1]|0?[1-9])\-(0?[1-9]|1[0-2])\-((19|20)?[0-9]{2}) # for DD-MM-YYYY
((19|20)?[0-9]{2})\/((1|2)[0-9]|3[0-1]|0?[1-9])\/(0?[1-9]|1[0-2]) # for YYYY/DD/MM
((19|20)?[0-9]{2})\-((1|2)[0-9]|3[0-1]|0?[1-9])\-(0?[1-9]|1[0-2]) # for YYYY-DD-MM
...

Finally, you need to combine them and have a single match with (expression1|expression2|...) :最后,您需要将它们组合起来并与(expression1|expression2|...)进行单个匹配:

\W(((1|2)[0-9]|3[0-1]|0?[1-9])\/(0?[1-9]|1[0-2])\/((19|20)?[0-9]{2})|((1|2)[0-9]|3[0-1]|0?[1-9])\-(0?[1-9]|1[0-2])\-((19|20)?[0-9]{2})|((19|20)?[0-9]{2})\/((1|2)[0-9]|3[0-1]|0?[1-9])\/(0?[1-9]|1[0-2])|((19|20)?[0-9]{2})\-((1|2)[0-9]|3[0-1]|0?[1-9])\-(0?[1-9]|1[0-2]))\W

I need the \\W at the begining and the end of regex.我需要在正则表达式的开头和结尾使用\\W this one check if you have anything (\\s, \\;, \\,, etc.).这一项检查您是否有任何东西(\\s、\\;、\\ 等)。

DEMO演示

You need to complete the missing combinations.您需要完成缺少的组合。

Enjoy ;)享受 ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM