English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Whether to use Java regular expressions to accept date strings (MM-dd-yyyy format)?

The following is with dd-MM-Regular expression for matching dates in yyyy format.

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

Match the date in the string in this format.

  • Compilecompile()The expression of the method of the Pattern class above.

  • Bypass the required input string asmatcher()The parameter of the method of the Pattern class, to obtain the Matcher object.

  • matches()If a match occurs, the method of the Matcher class returns true, otherwise it returns false. Therefore, call this method to verify the data.

Example1

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$";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Match 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 result

Date is valid

matches()The String class method accepts a regular expression and matches the current string with it, returning true if it matches and false otherwise. Therefore, to verify whether the given date (in string format) is in the required format-

  • Get the date string.

  • matches()Call the method by passing the above regular expression as a parameter to it.

Example2

import java.util.Scanner;
public class Just {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name:");
      String name = sc.nextLine();
      System.out.println("Enter your Date of birth:");
      String dob = sc.nextLine();
      //Regular expressions use MM-DD-YYY format accepts date
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4$";
      boolean result = dob.matches(regex);
      if(result) {
         System.out.println("Given date of birth is valid");
      } else {
         System.out.println("Given date of birth is not valid");
      }
   }
}

Output1

Enter your name:
Janaki
Enter your Date of birth:
26/09/1989
Given date of birth is not valid

Output2

Enter your name:
Janaki
Enter your Date of birth:
09/26/1989
Given date of birth is valid