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.
Phương thức lookingAt() của lớp Matcher khớp văn bản đầu vào với pattern, bắt đầu từ đầu vùng (region). Nếu khớp, trả về true, ngược lại false. Khác với phương thức matches(), phương thức này không yêu cầu khớp toàn bộ vùng để trả về true.
Ví dụ 1: lookingAt() khớp đầu chuỗi
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 pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.lookingAt()) {
System.out.println("Tìm thấy khớp");
} else {
System.out.println("Không tìm thấy khớp");
}
}
}
Kết quả
Tìm thấy khớp
Ví dụ 2: Kiểm tra chữ số ở đầu input nhiều dòng
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LookingAtExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập Chuỗi 1: ");
String input1 = sc.nextLine();
System.out.println("Nhập Chuỗi 2: ");
String input2 = sc.nextLine();
System.out.println("Nhập Chuỗi 3: ");
String input3 = sc.nextLine();
String input = input1 + "\n" + input2 + "\n" + input3;
System.out.println(input);
// Regex khớp từ chứa chữ số
String regex = ".*\\d+.*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
boolean bool = matcher.lookingAt();
if (bool) {
System.out.println("Đầu vào đã cho chứa chữ số");
} else {
System.out.println("Đầu vào đã cho không chứa chữ số nào");
}
}
}
Kết quả
Nhập Chuỗi 1: sample text2 Nhập Chuỗi 2: data Nhập Chuỗi 3: sample sample text2 data sample Đầu vào đã cho chứa chữ số
Lưu ý: lookingAt() chỉ kiểm tra từ đầu chuỗi (hoặc region start), không cần khớp hết chuỗi như matches().