Bạn có thể khớp cuối chuỗi đầu vào bằng metaký tự “\\z”.
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 = "[0-9]\\z";
// 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 sample text Không tìm thấy khớp
Kết quả 2
Nhập một chuỗi sample text 23 Tìm thấy khớp