Matcher toString() 方法在 Java 中带有示例
java.util.regex.Matcher 类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的对象。
Matcher 类的 **toString()** 方法返回一个字符串值,表示当前 matcher 对象的内容。
示例 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()); } }
输出
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 = "[#%&*]"; //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()); } }
输出
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=]
广告