Java中Matcher toString()方法的示例

java.util.regex.Matcher中的类代表一个引擎,进行各种匹配操作。此类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取此类的对象。

Matcher类的toString()方法返回一个字符串值,该字符串值表示当前匹配器对象的内容。

例子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 = "[#%&*]";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个Matcher对象
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //检索使用的模式
      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());
   }
}

输出结果

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

例子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 = "[#%&*]";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个Matcher对象
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //检索使用的模式
      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());
   }
}

输出结果

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