Các lớp ký tự (character classes) cho phép bạn chấp nhận một ký tự đơn từ một tập hợp ký tự cố định. Ví dụ:
- Biểu thức “[tmp]” khớp ký tự t hoặc m hoặc p.
- Biểu thức “[^tp]” khớp ký tự khác t hoặc p.
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();
// Biểu thức chính quy khớp ký tự t hoặc m hoặc p
String regex = "[tmp]";
// 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;
while (matcher.find()) {
count++;
}
System.out.println("Số lần xuất hiện: " + count);
}
}
Kết quả
Nhập một chuỗi hello how are you welcome to tutorialspoint Số lần xuất hiện: 6
Ví dụ 2
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 = "[^abcdef]";
// 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;
while (matcher.find()) {
count++;
}
System.out.println("Số lần xuất hiện: " + count);
}
}
Kết quả
Nhập một chuỗi Hello how are you welcome to tutorialspoint Số lần xuất hiện: 36