简体   繁体   English

正则表达式和日期模式匹配

[英]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. 对于无效的日期格式02/29/1975 (由于它不是a年),当我在该无效日期上尝试上述REGEX时,我不希望我的REGEX与该无效日期匹配。

Please suggest is there some way to achieve this. 请建议有一些方法可以实现此目的。

You will have to use DateFormatter in order to validate dates. 您将必须使用DateFormatter来验证日期。

Not only that, you will have to set the DateFormat's setLenient to false in order to catch those kinds of errors 不仅如此,您还必须将DateFormat的setLenient设置为false才能捕获此类错误。

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 您将看到它引发了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: 如果您未设置宽大处理,则DateFormat会尝试将其解析为一个方便的(尽管任意的)日期,例如:

02/29/1975 could be converted to 03/01/1975 03/01/1975 02/29/1975可以转换为03/01/1975

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

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