How to validate given date formats like MM-DD-YYYY using regex in java?


The java.util.regex package of java provides various classes to find particular patterns in character sequences.

The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely −

  • compile() − This method accepts a string representing a regular expression and returns an object of the Pattern object.

  • matcher() − This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.

Following is the regular expression to match date in dd-MM-yyyy format −

^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$

Therefore, to validate a date String of the format MM-DD-YYYY −

  • Compile the above mentioned regular expression using the compile() method of the Pattern class and retrieve the Pattern object.

  • Using the object obtained above, invoke the matcher() method by passing the required date string as a parameter and retrieve the Matcher object from this method.

  • The matches() of the Matcher class returns true in case of a match else, it returns false. Invoker this method on the matcher object obtained from the previous step.

Example

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchingDate {
   public static void main(String[] args) {
      String date = "01/12/2019";
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(date);
      boolean bool = matcher.matches();
      if(bool) {
         System.out.println("Date is valid");
      } else {
         System.out.println("Date is not valid");
      }
   }
}

Output

Date is valid

Updated on: 05-Dec-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements