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

matchs() method in Java and examples

java.util.regex.Matcher class represents an engine for executing various matching operations. This class does not have a constructor, and it can be used withmatches()method of java.util.regex.Pattern class creates/Get the object of this class.

This kind ofmatches()The method matches a string with a pattern represented by a regular expression (all given at object creation). In the case of a match, this method returns true, otherwise it returns false. For this method to return the correct result, the entire region should have a match.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchesExample {
   public static void main(String args[]) {
      //Read a string from the user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.next();
      //Regular expression to match words starting with a digit
      String regex = "^[0-9].*$";
      //Compile the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve the matcher object
      Matcher matcher = pattern.matcher(input);
      //Verify if a match occurs
      boolean bool = matcher.matches();
      if(bool) {
         System.out.println("The first character is a digit");
      } else {
         System.out.println("The first character is not a digit");
      }
   }
}

Output Result

Enter a String
4hiipla
The first character is a digit