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

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

thejava.util.regex.Matchera class representing an engine that performs various matching operations. This class has no constructor, and it can be used withmatches()The method of the java.util.regex.Pattern class creates/get an object of this class.

the twomatches()andfind()the try methods of the Matcher class to find matches according to the regular expression in the input string. If a match is found, both return true, and if no match is found, both methods return false.

The main difference lies inmatches()The method tries to match the entire area of the given input, that is, if you try to search for numbers in a line, this method returns true only when the input has numbers in all lines of the area.

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."
         + "\nThis is the second line in the text"
         + "\nThis is the third line in the text"
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.matches()) {
         else {
      }
         System.out.println("No matching item found");
      }
   }
}

Output Results

no match found

and thisfind()The method tries to find the next substring that matches the pattern, that is, if at least one match is found in this area, this method returns true.

If you want to see the following example, we try to match a specific line with the middle number.

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."
         + "\nThis is the second line in the text"
         + "\nThis is the third line in the text"
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      //System.out.println("Current range: "+input.substring(regStart, regEnd));
      if(matcher.find()) {
         else {
      }
         System.out.println("No matching item found");
      }
   }
}

Output Results

Find Matching Items