java.util.regex.Matcher class แสดงถึงเอ็นจิ้นที่ดำเนินการจับคู่ต่างๆ ไม่มีตัวสร้างสำหรับคลาสนี้ คุณสามารถสร้าง/รับวัตถุของคลาสนี้โดยใช้เมธอดmatch() ของคลาส java.util.regex.Pattern
ทั้ง match() และ fin() เมธอดของคลาส Matcher พยายามค้นหาการจับคู่ตามนิพจน์ทั่วไปในสตริงอินพุต ในกรณีของการจับคู่ ทั้งคู่คืนค่าจริงและหากไม่พบการจับคู่ทั้งสองวิธีคืนค่าเท็จ
ความแตกต่างหลักคือเมธอดmatch() พยายามจับคู่ภูมิภาคทั้งหมดของอินพุตที่ระบุ เช่น หากคุณกำลังพยายามค้นหาตัวเลขในบรรทัด วิธีการนี้จะคืนค่าเป็น จริง เฉพาะในกรณีที่อินพุตมีตัวเลขในทุกบรรทัดในภูมิภาค
ตัวอย่าง1
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";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} ผลลัพธ์
Match not found
ในขณะที่เมธอด find() พยายามค้นหาสตริงย่อยถัดไปที่ตรงกับรูปแบบ เช่น หากพบอย่างน้อยหนึ่งรายการที่ตรงกันในภูมิภาค วิธีการนี้จะคืนค่าเป็นจริง
หากคุณพิจารณาตัวอย่างต่อไปนี้ เรากำลังพยายามจับคู่บรรทัดใดบรรทัดหนึ่งโดยมีตัวเลขอยู่ตรงกลาง
ตัวอย่าง2
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";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(input);
//System.out.println("Current range: "+input.substring(regStart, regEnd));
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} ผลลัพธ์
Match found