Bạn có thể khớp đầu chuỗi đầu vào bằng metaký tự “\\A”.
Ví dụ
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// Đọc chuỗi từ người dùng
System.out.println("Nhập một chuỗi");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\A[0-9]";
// Biên dịch biểu thức chính quy
Pattern pattern = Pattern.compile(regex);
// Lấy đối tượng matcher
Matcher matcher = pattern.matcher(input);
int count = 0;
if (matcher.find()) {
System.out.println("Tìm thấy khớp ");
} else {
System.out.println("Không tìm thấy khớp ");
}
}
}
Kết quả 1
Nhập một chuỗi 12 sample text Tìm thấy khớp
Kết quả 2
Nhập một chuỗi sample text Không tìm thấy khớp