Metaký tự “$” khớp với cuối của một chuỗi cụ thể, tức là nó khớp với ký tự cuối cùng của chuỗi. Ví dụ:
- Biểu thức “\\d$” khớp chuỗi/dòng kết thúc bằng chữ số.
- Biểu thức “[a-z]$” khớp chuỗi/dòng kết thúc bằng chữ cái thường.
Ví dụ 1
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-zA-Z0-9//s]$";
// 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);
if (matcher.matches()) {
System.out.println("Khớp xảy ra");
} else {
System.out.println("Không khớp");
}
}
}
Kết quả 1
Nhập một chuỗi this is sample text# Khớp xảy ra
Kết quả 2
Nhập một chuỗi hello how are you Không khớp
Ví dụ 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "\\.$";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập 5 chuỗi đầu vào: ");
String input[] = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
// Tạo đối tượng Pattern
Pattern p = Pattern.compile(regex);
for (int i = 0; i < 5; i++) {
// Tạo đối tượng Matcher
Matcher m = p.matcher(input[i]);
if (m.find()) {
System.out.println("Chuỗi " + i + " kết thúc bằng '.'");
}
}
}
}
Kết quả
Nhập 5 chuỗi đầu vào: hello how are you. where do you live what is your name. welcome to tutorialspoint The Biggest Online Tutorials Library. Chuỗi 0 kết thúc bằng '.' Chuỗi 2 kết thúc bằng '.' Chuỗi 4 kết thúc bằng '.'