Phần biểu thức/metaký tự “$” khớp với cuối dòng.
Ví dụ 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EndWith {
public static void main(String args[]) {
String regex = "Tutorialspoint$";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
System.out.println("Số lần khớp: " + count);
}
}
}
Kết quả
Số lần khớp: 1
Ví dụ 2
Chương trình Java sau chấp nhận 5 chuỗi từ người dùng và in ra các chuỗi kết thúc bằng chữ số.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EndingwithDigit {
public static void main(String args[]) {
String regex = "^.*[0-9]$";
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);
System.out.println("Các chuỗi kết thúc bằng chữ số: ");
for (int i = 0; i < 5; i++) {
// Tạo đối tượng Matcher
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
Kết quả
Nhập 5 chuỗi đầu vào: sample string 1 sample string 2 test data hello 3264533 3546373 7653 Các chuỗi kết thúc bằng chữ số: sample string 1 sample string 2 3264533 3546373 7653