คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern
Anchoring bounds ใช้จับคู่ region matches เช่น ^ และ $ โดยค่าเริ่มต้น matcher ใช้ anchoring bounds คุณสามารถสลับจาก anchoring bounds เป็น non-anchoring bounds โดยใช้เมธอด useAnchoringBounds()
เมธอด hasAnchoringBounds() ของคลาส (Matcher) นี้ตรวจสอบว่ matcher ปัจจุบันใช้ anchoring bounds หรือไม่ หากใช่ คืนค่า true มิฉะนั้น false
ตัวอย่างที่ 1: ค่าเริ่มต้น (anchoring bounds = true)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasAnchoringBoundsExample {
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);
// ตรวจสอบ anchoring bounds
boolean bool = matcher.hasAnchoringBounds();
// ตรวจสอบการจับคู่
if (bool) {
System.out.println("Current matcher uses anchoring bounds");
} else {
System.out.println("Current matcher uses non-anchoring bounds");
}
if (matcher.matches()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
Output
Current matcher uses anchoring bounds Match not found
ตัวอย่างที่ 2: ปิด anchoring bounds
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Trail {
public static void main(String args[]) {
// อ่านค่าสตริง
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
// Regular expression เพื่อหาตัวเลข
String regex = ".*\\d+.*";
// คอมไพล์ regular expression
Pattern pattern = Pattern.compile(regex);
// พิมพ์ regular expression
System.out.println("Compiled regular expression: " + pattern.toString());
// ดึง Matcher object
Matcher matcher = pattern.matcher(input);
matcher.useAnchoringBounds(false);
boolean hasBounds = matcher.hasAnchoringBounds();
if (hasBounds) {
System.out.println("Current matcher uses anchoring bounds");
} else {
System.out.println("Current matcher uses non-anchoring bounds");
}
// ตรวจสอบว่ามีการจับคู่เกิดขึ้นหรือไม่
if (matcher.matches()) {
System.out.println("Given String contains digits");
} else {
System.out.println("Given String does not contain digits");
}
}
}
Output
Enter input string hello sample 2 Compiled regular expression: .*\d+.* Current matcher uses non-anchoring bounds Given String contains digits