Java 中的 Matcher toString() 方法示例

javaobject oriented programmingprogramming更新于 2024/5/8 14:04:17

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

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("输入输入文本:");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个 Matcher 对象
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //检索使用的模式
      System.out.println("给定文本中有"+count+" 个特殊 [# % & *] 字符");
      System.out.println("以下是使用的匹配器的字符串格式:\n"+matcher.toString());
   }
}

输出

输入文本:
Hello# How # are# you *& welcome to T#utorials%point
给定文本中有 7 个特殊的 [# % & *] 字符
以下是使用的匹配器的字符串格式:
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("输入输入文本:");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个 Matcher 对象
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //检索使用的模式
      System.out.println("给定文本中有"+count+" 个特殊 [# % & *] 字符");
      System.out.println("以下是使用的匹配器的字符串格式:\n"+matcher.toString());
   }
}

输出

输入文本:
Hello# How # are# you *& welcome to T#utorials%point
给定文本中有 7 个特殊的 [# % & *] 字符
以下是使用的匹配器的字符串格式:
java.util.regex.Matcher[pattern=[#%&*] region=0,52 lastmatch=]

相关文章


有用资源