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=]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP