Lớp ký tự POSIX \p{XDigit} khớp với các ký tự thập lục phân (hexadecimal): 0-9, a-f, A-F. Tương đương với [0-9a-fA-F].
Ví dụ 1: Đếm ký tự hex
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SpaceCharacters {
public static void main(String args[]) {
System.out.println("Nhập một chuỗi:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "[\\p{XDigit}]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số ký tự hexadecimal: " + count);
}
}
Kết quả mẫu
Nhập một chuỗi: Bb12 c! Số ký tự hexadecimal: 5
Giải thích: B, b, 1, 2, c là 5 ký tự hex. Tab (\t) và ! không tính.
Ví dụ 2: Lọc chuỗi chứa ký tự hex
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// Regex: chuỗi chứa ít nhất 1 ký tự hex
String regex = "^.*\\p{XDigit}.*$";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập 5 chuỗi:");
String[] input = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
Pattern p = Pattern.compile(regex);
System.out.println("Chuỗi chứa ký tự hexadecimal:");
for (int i = 0; i < 5; i++) {
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
Kết quả mẫu
Nhập 5 chuỗi: sample 123 xyz @## DEF01 Chuỗi chứa ký tự hexadecimal: sample 123 DEF01
Ứng dụng thực tế
- Validate mã màu hex:
^#[0-9a-fA-F]{6}$hoặc^#\p{XDigit}{6}$ - Kiểm tra chuỗi hex hợp lệ:
^\p{XDigit}+$ - Parse dữ liệu nhị phân/hex dump.
Lưu ý
- Trong Java string:
"\\p{XDigit}". - Khác với
\p{Digit}(chỉ 0-9),\p{XDigit}bao gồm cả A-F/a-f.