想问一下 java中如何判断一个字符串时间 是否是YYYY-MM-DD 正则怎么写啊 谢谢
YYYY-MM-DD
The simplest way to write
[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] \d\d\d\d-\d\d-\d\d \d{4}-\d{2}-\d{2}
Improvements
1 Limit the first two digits of the year to 19 or 20
(19|20)[0-9][0-9]-[0-9][0-9]-[0-9][0-9]
2 Limit the months to 01 to 12
(19|20)[0-9][0-9]-(0[1-9]|1[0-2])-[0-9][0-9]
3 Limit the date to 01 to 31
(19|20)[0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[01]) (19|20)[0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])
In fact, I suggest you use SimpleDateFormat to parse it. If there is no exception, it will be the date format you want.
SimpleDateFormat
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); s.parse(source)
This way you can match the date string
public class Q1010000002719930 { public static void main(String[] args) { matchDateString("2015-4-30"); //false matchDateString("2015-04-30"); //true matchDateString("2015-02-20"); //true } private static void matchDateString(String string) { Pattern pattern = Pattern.compile("(\d){4}-(\d){2}-(\d){2}"); Matcher matcher = pattern.matcher(string); System.out.println(matcher.find()); } }
(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[13579][26])00))-02-29)
Reference
YYYY-MM-DD
The simplest way to write
Improvements
1 Limit the first two digits of the year to 19 or 20
2 Limit the months to 01 to 12
3 Limit the date to 01 to 31
In fact, I suggest you use
SimpleDateFormat
to parse it. If there is no exception, it will be the date format you want.This way you can match the date string
Reference