我有一个看起来像这样的字符串:20/11/2019

我想检查一下:


第一个数字在1到31之间
第二个数字在1到12之间
第三个数字在2000到2999之间


数字之间用“ /”分隔。



我已经尝试过使用正则表达式,但是我并不熟悉它。

if (ExpDate.matches("[1-31]/[1-12]/[2000-2999]")){
//something happens
}


有什么方法可以正确完成此操作吗?

在此先感谢您的帮助。

最佳答案

假设这不仅是使用正则表达式的一种练习,imho最好使用为该工作量身定制的工具。特别是因为可能会假定您将在应用程序中使用日期。考虑使用DateTimeFormatterLocalDate来管理相关对象。

      DateTimeFormatter dfmtr =
            DateTimeFormatter.ofPattern("dd/MM/uuuu").withResolverStyle(
                  ResolverStyle.STRICT);

      for (String testDate : new String[] {
            "20/11/1999", "31/11/2000", "20/11/2019", "32/33/2001",
            "29/02/2016", "29/02/2015"
      }) {
         try {
            LocalDate d = LocalDate.parse(testDate, dfmtr);
            int year = d.getYear();
            if (year < 2000 || year >= 3000) {
               throw new DateTimeParseException(
                     "Year (" + year + ") out of specified range", "uuuu", 6);
            }

            System.out.println("VALID: " + testDate);
         }
         catch (DateTimeParseException dtpe) {
            System.out.println("INVALID DATE: " + dtpe.getLocalizedMessage());
         }
      }



您甚至可以重新格式化错误消息以匹配默认消息,或者使用您自己的错误消息代替默认消息。这也照顾of年和给定月份的适当日子。

10-07 19:18
查看更多