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

Example of Matcher toMatchResult() method in Java

java.util.regex.Matcher class represents the engine for executing various matching operations. This class has no constructor and can be usedmatches()The method of the class java.util.regex.Pattern to create/Get an object of this class.

This (matcher)'stoMatchResult()The method returns the current matching state of the matcher.

Example1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ToMatchResultExample {
   public static void main(String[] args) {
      String str = "<p>This <b>is</b> an <b>example</b>.</p>";
      //Regular expressions to match the content of bold tags
      String regex = "<b>(\\S+)</b>";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Match the compiled pattern in the string
      System.out.println("State of the matcher: ");
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.toMatchResult());
         String result = matcher.group(1);
      }
      matcher = matcher.reset("<p>this is another <b>line</b>.</p>");
      matcher.find();
      System.out.println("");
      System.out.println("State of the matcher after resetting it: \n"+matcher.toMatchResult());
   }
}

Output result

State of the matcher:
java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,40 lastmatch=<b>is</b>]
java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,40 lastmatch=<b>example</b>]
State of the matcher after resetting it:
java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,35 lastmatch=<b>line</b>]

Example2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ToMatchResultExample {
   public static void main(String[] args) {
      String regex = "[#];"
      System.out.println("Enter a string:");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      System.out.println("Match state:");
      //Found match
      while(matcher.find()) {
         System.out.println(matcher.toMatchResult());
      }
   }
}

Output result

Enter a string:
#This #is #a #sample #text
Match state:
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]
java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]