คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern
ใน regular expressions lookbehind และ lookahead constructs ใช้จับคู่ pattern เฉพาะที่มาก่อนหรือตามหลัง pattern อื่นๆ เช่น หากคุณต้องการยอมรับสตริงที่ยอมรับ 5 ถึง 12 ตัวอักษร regular expression จะเป็น −
"\\A(?=\\w{6,10}\\z)"
โดยค่าเริ่มต้น ขอบเขตของ matcher region ไม่โปร่งใสต่อ lookahead, lookbehind และ boundary matching กล่าวคือ constructs เหล่านี้ไม่สามารถจับคู่เนื้อหาของข้อความอินพุตนอกเหนือจากขอบเขต region ได้ −
ตัวอย่างที่ 1: โดยไม่ใช้ transparent bounds
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class useTransparentBoundsExample {
public static void main(String[] args) {
// Regular expression ยอมรับ 6 ถึง 10 ตัวอักษร
String regex = "\\A(?=\\w{6,10}\\z)";
System.out.println("Enter 5 to 12 characters: ");
String input = new Scanner(System.in).next();
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(input);
// ตั้ง region ให้กับสตริงอินพุต
matcher.region(0, 4);
// สลับไปใช้ transparent bounds
if (matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
Output
Enter 5 to 12 characters: sampleText Match not found
เมธอด useTransparentBounds() ของคลาสนี้รับค่า boolean และ หากคุณส่ง true ให้เมธอดนี้ matcher ปัจจุบันจะใช้ transparent bounds และหากส่ง false จะใช้ non-transparent bounds
ตัวอย่างที่ 2: ใช้ transparent bounds
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
// Regular expression ยอมรับ 6 ถึง 10 ตัวอักษร
String regex = "\\A(?=\\w{6,10}\\z)";
System.out.println("Enter 5 to 12 characters: ");
String input = new Scanner(System.in).next();
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(input);
// ตั้ง region ให้กับสตริงอินพุต
matcher.region(0, 4);
// สลับไปใช้ transparent bounds
matcher = matcher.useTransparentBounds(true);
if (matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
Output
Enter 5 to 12 characters: sampletext Match found