คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern
เมธอด toString() ของคลาส Matcher คืนค่าสตริงที่แทนเนื้อหาของ matcher object ปัจจุบัน
ตัวอย่างที่ 1: นับอักขระพิเศษ แล้วดู toString()
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 object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
// ดึง Pattern ที่ใช้
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());
}
}
Output
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: ซ้ำตัวอย่างที่ 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 object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
// ดึง Pattern ที่ใช้
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());
}
}
Output
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=]