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

Ejemplo de método toString() de Matcher en Java

Estejava.util.regex.Matcher conLa clase representa un motor que realiza varias operaciones de coincidencia. Esta clase no tiene constructor, se puede usarmatches()El método de la clase java.util.regex.Pattern crea/obtiene el objeto de esta clase.

La clase MatchertoString()El método devuelve un valor de cadena que representa el contenido del objeto del matcher actual.

Ejemplo1

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("Ingrese texto de entrada: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //Crear un objeto de patrón
      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());
   }
}

Resultado de salida

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=[#%&*]52 lastmatch=]

Ejemplo2

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("Ingrese texto de entrada: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //Crear un objeto de patrón
      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());
   }
}

Resultado de salida

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=[#%&*]52 lastmatch=]