The following is the regular expression to match the date in the dd-MM-yyyy format.
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$
To match a date in a string in that format.
Compile the above expression of the compile() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
The matches() method of the Matcher class returns true if a match occurs else it returns false. Therefore, invoke this method to validate the data.
Example 1
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
The matches() method of the String class accepts a regular expression and matches the current string with it and returns true in case of a match and else returns false. Therefore, to verify if the given date (in string format) is in the required format −
- Get the date string.
- Invoke the matches() method on it by passing the above regular expression as a parameter to it.
Example 2
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 expression to accept date in MM-DD-YYY format 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"); } } }
Output 1
Enter your name: Janaki Enter your Date of birth: 26/09/1989 Given date of birth is not valid
Output 2
Enter your name: Janaki Enter your Date of birth: 09/26/1989 Given date of birth is valid