Matcher find() method in Java with Example


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 find() method of this class tries to find the next subsequent input matching the current Matcher object, in case of the match this method returns true else it returns false.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "(\D)";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //verifying whether match occurred
      if(matcher.find()) {
         System.out.println("Given string contain non-digit characters");
      } else {
         System.out.println("Given string does not contain non-digit characters");
      }
   }
}

Output

Enter input string
11245#
Given string contain non-digit characters

Updated on: 19-Nov-2019

608 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements