Pattern matches() method in Java with examples

JavaObject Oriented ProgrammingProgramming

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.

The matches() method of the Pattern class accepts −

  • A string value representing the regular expression.

  • An object of the CharSequence class representing the input string.

On invocation, this method matches the input string against the regular expression. This method returns a boolean value which is true in-case of a match else, false.


import java.util.Scanner;
import java.util.regex.Pattern;
public class MatchesExample {
   public static void main(String[] args) {
      //Getting the date
      Scanner sc = new Scanner(;
      System.out.println("Enter date string in [dd/mm/yyy] format: ");
      String date =;
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      //Creating a pattern object
      boolean result = Pattern.matches(regex, date);
      if(result) {
         System.out.println("Date is valid");
      } else {
         System.out.println("Date is not valid");

Output 1

Enter date string in [dd/mm/yyy] format:
Date is valid

Output 2

Enter date string in [dd/mm/yyy] format:
Date is not valid
Updated on 20-Nov-2019 05:44:56