Matcher toString() method in Java with Examples

JavaObject Oriented ProgrammingProgramming

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 toString() method of the Matcher class returns a string value representing the contents of the current matcher object.

Example 1

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 = "[#%&*]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Retrieving 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

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=]

Example 2

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 = "[#%&*]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Retrieving 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

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=]
raja
Published on 20-Nov-2019 06:38:53
Advertisements