Nick26
Nick26

Reputation: 43

Check a string value using multiple different number ranges

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

I would like to check if:

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.

Upvotes: 0

Views: 48

Answers (1)

WJS
WJS

Reputation: 40034

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.

Upvotes: 1

Related Questions