简体   繁体   中英

Regex and Date pattern matching

Below is the regex I am have:

Pattern ddpat = Pattern.compile( "(\\d{1,2}/\\d{1,2}/\\d{4})" );

For an invalid date pattern 02/29/1975 (Since it is not a leap year), when I try the above REGEX on this invalid date, I don't want my REGEX to match this invalid date.

Please suggest is there some way to achieve this.

You will have to use DateFormatter in order to validate dates.

Not only that, you will have to set the DateFormat's setLenient to false in order to catch those kinds of errors

public static void main(String[] args) throws ParseException {
    String d = "02/29/1975";
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    sdf.setLenient(false);
    Date date = sdf.parse(d);
    System.out.println(date);
}

You will see that it throws the ParseException

If you don't set up the leniency, then the DateFormat will attempt to parse it to a convenient albeit arbitrary Date for example:

02/29/1975 could be converted to 03/01/1975

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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