0

I have a string that looks like this: 20/11/2019

I would like to check if:

  • The first number is between 1 and 31
  • The second number is between 1 and 12
  • The third number is between 2000 and 2999

The numbers are separated by "/".


I have tried using regex, but I'm not familiar with it.

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

Is there any way to accomplish this correctly?

Thanks in advance for any help.

2
  • your approach is right, so you just need to create the proper regular expression, for example for year number you can use 2[0-9][0-9][0-9] Commented Nov 2, 2019 at 16:24
  • Thanks @AnatoliyR! I changed the day and month to that of your year format, and it works perfectly now :) Commented Nov 2, 2019 at 16:34

1 Answer 1

1

Assuming this is not just an exercise in using regular expressions, imho is is best to use the tools made for the job. Especially since one might presume you would be using dates latter on in your application. Consider using DateTimeFormatter and LocalDate to manage related objects.

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

You can even reformat the error message to match the default one or use your own in place of the default one. This also takes care of leap years and proper days for given month.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.