What is difference between matches() and find() in Java Regex?


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.

Both matches() and find() methods of the Matcher class tries to find the match according to the regular expression in the input string. In case of a match, both returns true and if a match is not found both methods return false.

The main difference is that the matches() method try to match the entire region of the given input i.e. if you are trying to search for digits in a line this method returns true only if the input has digits in all lines in the region.

Example1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String regex = "(.*)(\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between. "
         + "\n This is the second line in the text "
         + "\n This is third line in the text";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Match not found

Whereas, the find() method tries to find the next substring that matches the pattern i.e. if at least one match found in the region this method returns true.

If you consider the following example, we are trying to match a particular line with digits in the middle of it.

Example2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String regex = "(.*)(\d+)(.*)";
      String input = "This is a sample Text, 1234, with numbers in between. "
         + "\n This is the second line in the text "
         + "\n This is third line in the text";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      //System.out.println("Current range: "+input.substring(regStart, regEnd));
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Match found

Updated on: 20-Nov-2019

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements