Pattern matches() method in Java with examples


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.

Example

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.in);
      System.out.println("Enter date string in [dd/mm/yyy] format: ");
      String date = sc.next();
      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:
01/12/2019
Date is valid

Output 2

Enter date string in [dd/mm/yyy] format:
2019-21-12
Date is not valid

Updated on: 20-Nov-2019

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements