java - 正则表达式 表示YYYY-MM-DD
巴扎黑
巴扎黑 2017-04-17 13:33:12
0
4
823

想问一下
java中如何判断一个字符串时间 是否是YYYY-MM-DD 正则怎么写啊 谢谢

巴扎黑
巴扎黑

reply all(4)
左手右手慢动作

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 s =  new SimpleDateFormat("yyyy-MM-dd");
s.parse(source)
PHPzhong

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());
    }
}
PHPzhong
(([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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template