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

Matcher toString() method in Java with example

Thisfrom java.util.regex.MatcherThis class represents an engine for performing various matching operations. This class has no constructor and can be usedmatches()The method of class java.util.regex.Pattern creates/Get an object of this class.

Method of Matcher classtoString()The method returns a string value representing the content of the current matcher object.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ToStringExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*];
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Search pattern used
      System.out.println("The are "+count+" special [# % & *]; characters in the given text");
      System.out.println("Following is the string format of the matcher used: \n"+matcher.toString());
   }
}

Output Result

Enter input text:
Hello# How # are # you *& welcome to T#utorials%point
The are 7 special [# % & *] characters in the given text
Following is the string format of the matcher used:
java.util.regex.Matcher[pattern=[#%&*], region=0,52 lastmatch=]

Example2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ToStringExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*];
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Search pattern used
      System.out.println("The are "+count+" special [# % & *]; characters in the given text");
      System.out.println("Following is the string format of the matcher used: \n"+matcher.toString());
   }
}

Output Result

Enter input text:
Hello# How # are # you *& welcome to T#utorials%point
The are 7 special [# % & *] characters in the given text
Following is the string format of the matcher used:
java.util.regex.Matcher[pattern=[#%&*], region=0,52 lastmatch=]