Lớp java.util.regex.Matcher đại diện cho một engine thực hiện các phép toán khớp khác nhau. Không có constructor cho lớp này, bạn có thể tạo/nhận đối tượng của lớp này bằng phương thức matcher() của lớp java.util.regex.Pattern.
Trong biểu thức chính quy, các cấu trúc lookbehind và lookahead được dùng để khớp một pattern cụ thể đi trước hoặc đi sau pattern khác. Ví dụ, nếu bạn cần chấp nhận chuỗi 5-12 ký tự, regex sẽ là:
"\\A(?=\\w{6,10}\\z)"
Mặc định, ranh giới vùng của matcher không trong suốt đối với lookahead, lookbehind và khớp ranh giới, tức là các cấu trúc này không thể khớp nội dung vượt quá ranh giới vùng.
Phương thức hasTransparentBounds() kiểm tra xem matcher hiện tại có dùng transparent bounds hay không. Nếu có, trả về true, ngược lại false.
Ví dụ 1: Mặc định non-transparent
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasTransparentBounds {
public static void main(String[] args) {
String regex = "\\A(?=\\w{6,10}\\z)";
System.out.println("Nhập 5 đến 12 ký tự: ");
String input = new Scanner(System.in).next();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
matcher.region(0, 4);
if (matcher.find()) {
System.out.println("Tìm thấy khớp");
} else {
System.out.println("Không tìm thấy khớp");
}
boolean bool = matcher.hasTransparentBounds();
if (bool) {
System.out.println("Matcher hiện tại dùng transparent bounds");
} else {
System.out.println("Matcher hiện tại dùng non-transparent bounds");
}
}
}
Kết quả
Nhập 5 đến 12 ký tự: sampletext Không tìm thấy khớp Matcher hiện tại dùng non-transparent bounds
Ví dụ 2: Sau khi bật transparent bounds
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HasTransparentBounds {
public static void main(String[] args) {
String regex = "\\A(?=\\w{6,10}\\z)";
System.out.println("Nhập 5 đến 12 ký tự: ");
String input = new Scanner(System.in).next();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
matcher.region(0, 4);
matcher.useTransparentBounds(true);
if (matcher.find()) {
System.out.println("Tìm thấy khớp");
} else {
System.out.println("Không tìm thấy khớp");
}
boolean bool = matcher.hasTransparentBounds();
if (bool) {
System.out.println("Matcher hiện tại dùng transparent bounds");
} else {
System.out.println("Matcher hiện tại dùng non-transparent bounds");
}
}
}
Kết quả
Nhập 5 đến 12 ký tự: sampletext Tìm thấy khớp Matcher hiện tại dùng transparent bounds