Regex
^(?=.{10,255}$)(?:0x)?\p{XDigit}{2}(?:\p{XDigit}{2})*$
Giải thích
^ - đầu chuỗi
(?=.{10,255}$) - lookahead: độ dài 10-255 ký tự
(?:0x)? - prefix "0x" tùy chọn (non-capturing)
\p{XDigit}{2} - đúng 2 hex digit
(?:\p{XDigit}{2})* - 0 hoặc nhiều cặp hex digit (đảm bảo độ dài chẵn)
$ - cuối chuỗi
Ví dụ 1: Validate nhiều số
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaExample51 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] nums = new String[5];
for (int i = 0; i < nums.length; i++) {
System.out.println("Nhập số hex: ");
nums[i] = sc.nextLine();
}
String regex = "^(?=.{10,255}$)(?:0x)?\\p{XDigit}{2}(?:\\p{XDigit}{2})*$";
Pattern pattern = Pattern.compile(regex);
for (String hex : nums) {
Matcher matcher = pattern.matcher(hex);
if (matcher.find()) {
System.out.println(hex + " is valid");
} else {
System.out.println(hex + " is not valid");
}
}
}
}
Kết quả
Nhập số hex: 0x1234567890
Nhập số hex: 123456789
Nhập số hex: 123456789012
Nhập số hex: sfdgdf35364
Nhập số hex: $@%#BV#*
0x1234567890 is valid
123456789 is not valid (độ dài lẻ 9)
123456789012 is valid
sfdgdf35364 is not valid (chứa ký tự không hex)
$@%#BV#* is not valid
Ví dụ 2: String.matches()
String regex = "^(?=.{10,255}$)(?:0x)?\\p{XDigit}{2}(?:\\p{XDigit}{2})*$";
System.out.println("0x1234567890".matches(regex)); // true
System.out.println("024587545".matches(regex)); // false (lẻ 9 ký tự)
Lưu ý
- \p{XDigit} = [0-9A-Fa-f] (hex digit Unicode).
- Độ dài chẵn: bắt đầu 2 digit, sau đó thêm cặp (2n).
- Giới hạn 255 ký tự tránh DoS regex.