The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The matches() method of this class matches the string with, the pattern represented by the regular expression (both given while creating this object). In the case of a match, this method returns true else it returns false. For the result of this method to be true, 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[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.next(); //Regular expression to match words that starts with digits String regex = "^[0-9].*$"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); //verifying whether match occurred boolean bool = matcher.matches(); if(bool) { System.out.println("First character is a digit"); } else{ System.out.println("First character is not a digit"); } } }
Output
Enter a String 4hiipla First character is a digit