Java yyyy-mm-dd 的正则表达式日期验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22061723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex date validation for yyyy-mm-dd
提问by Romaine Herrera
what is the regex for the date format yyyy-mm-dd?
日期格式 yyyy-mm-dd 的正则表达式是什么?
I want to validate the email from edittext and check if it matches the regex.
我想验证来自 edittext 的电子邮件并检查它是否与正则表达式匹配。
回答by Hamid Shatu
You can use this regex to get the yyyy-MM-dd format: ((?:19|20)\d\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])
您可以使用此正则表达式来获取 yyyy-MM-dd 格式: ((?:19|20)\d\d)-(0?[1-9]|1[012])-([12][0 -9]|3[01]|0?[1-9])
You can find example for date validation: How to validate date with regular expression.
您可以找到日期验证的示例:如何使用正则表达式验证日期。
回答by wumpz
A simple one would be
一个简单的将是
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
但这并不限制月份为 1-12,天数为 1 至 31。
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
还有更复杂的检查,就像其他答案一样,顺便说一下非常聪明的检查。然而,您必须检查有效日期,因为没有检查一个月是否有 28、30 或 31 天。
回答by Vinod
This will match yyyy-mm-dd
and also yyyy-m-d
:
这将匹配yyyy-mm-dd
并且还yyyy-m-d
:
^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$
If you're looking for an exact match for yyyy-mm-dd
then try this
如果你正在寻找一个完全匹配的yyyy-mm-dd
然后试试这个
^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$
or use this one if you need to find a date inside a string like The date is 2017-11-30
或者如果您需要在字符串中查找日期,请使用此方法 The date is 2017-11-30
\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*
回答by zainoz.zaini
you can test this expression:
你可以测试这个表达式:
^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$
Description:
validates a yyyy-mm-dd, yyyy mm dd, or yyyy/mm/dd date
说明:
验证 yyyy-mm-dd、yyyy mm dd 或 yyyy/mm/dd 日期
makes sure day is within valid range for the month - does NOT validate Feb. 29 on a leap year, only that Feb. Can have 29 days
确保日期在该月的有效范围内 - 不验证闰年的 2 月 29 日,只有 2 月可以有 29 天
Matches (tested) : 0001-12-31 | 9999 09 30 | 2002/03/03
匹配(已测试):0001-12-31 | 9999 09 30 | 2002/03/03