Home  >  Article  >  Java  >  Accept date string (MM-dd-yyyy format) using Java regex?

Accept date string (MM-dd-yyyy format) using Java regex?

WBOY
WBOYforward
2023-09-07 18:05:021333browse

Accept date string (MM-dd-yyyy format) using Java regex?

The following is a regular expression that matches dates in dd-MM-yyyy format.

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

Match dates in this format string.

  • Compile the expression Pattern class of the compile() method above.

  • Bypasses the required input string as an argument to the matcher() method of the Pattern class to obtain a Matcher object.

  • The matches() method of the Matcher class returns true if a match occurs, otherwise it returns false. Therefore, this method is called 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, returning true if it matches, otherwise it returns false. So, to verify that a given date (in string format) conforms to the required format -

  • Get the date string.
  • Call the matches() method, 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

The above is the detailed content of Accept date string (MM-dd-yyyy format) using Java regex?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete