คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern
ทั้ง matches() และ find() เมธอดของคลาส Matcher พยายามหาจุดจับคู่ตาม regular expression ในสตริงอินพุต หากจับคู่ได้ทั้งคู่คืนค่า true และหากไม่พบการจับคู่ทั้งคู่คืนค่า false
ความแตกต่างหลักคือ เมธอด matches() พยายามจับคู่ทั้ง region ของอินพุตที่ให้มา กล่าวคือ หากคุณพยายามค้นหาตัวเลขในบรรทัด เมธอดนี้คืนค่า true ก็ต่อเมื่ออินพุตมีตัวเลขในทุกบรรทัดใน region
ตัวอย่างที่ 1: ใช้ matches() - ไม่จับคู่
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between. " + "\n This is the second line in the text " + "\n This is third line in the text";
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
Output
Match not found
ในขณะที่ เมธอด find() พยายามหา substring ถัดไปที่จับคู่กับ pattern กล่าวคือ หากมีการจับคู่อย่างน้อยหนึ่งจุดใน region เมธอดนี้คืนค่า true
หากคุณพิจารณาตัวอย่างต่อไปนี้ เรากำลังพยายามจับคู่บรรทัดเฉพาะที่มีตัวเลขอยู่กลาง
ตัวอย่างที่ 2: ใช้ find() - จับคู่ได้
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between. " + "\n This is the second line in the text " + "\n This is third line in the text";
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
Output
Match found