Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Java Regex: Hexadecimal Number > 10 ตัว และ ความยาวเป็นเลขคู่

Regex สำหรับ hexadecimal number ความยาวมากกว่า 10 และเป็นเลขคู่:

^(?=.{10,255}$)(?:0x)?\p{XDigit}{2}(?:\p{XDigit}{2})*$

อธิบาย Regex

ตัวอย่าง 1: ตรวจสอบ 5 ค่า

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("Enter a hexa-decimal number: ");
            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");
            }
        }
    }
}

ผลลัพธ์

Enter a hexa-decimal number: 0x1234567890
Enter a hexa-decimal number: 123456789
Enter a hexa-decimal number: 123456789012
Enter a hexa-decimal number: sfdgdf35364
Enter a hexa-decimal number: $@%#BV#*
0x1234567890 is valid
123456789 is not valid
123456789012 is valid
sfdgdf35364 is not valid
$@%#BV#* is not valid

ตัวอย่าง 2: ใช้ String.matches()

import java.util.Scanner;

public class JavaExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a hexa-decimal number: ");
        String name = sc.nextLine();
        String regex = "^(?=.{10,255}$)(?:0x)?\\p{XDigit}{2}(?:\\p{XDigit}{2})*$";
        boolean result = name.matches(regex);
        
        if (result) {
            System.out.println("Given number is valid");
        } else {
            System.out.println("Given number is not valid");
        }
    }
}

ผลลัพธ์

Enter your name: 0x1234567890
Given name is valid

Enter a hexa-decimal number: 024587545
Given number is not valid

อธิบายผลลัพธ์

ส่วนRegexความหมาย
Start^เริ่มต้นสตริง
Length check(?=.{10,255}$)Positive lookahead: ความยาว 10-255 chars
Optional 0x(?:0x)?prefix "0x" optional (non-capturing)
First pair\p{XDigit}{2}2 hex digits พอดี (บังคับคู่แรก)
More pairs(?:\p{XDigit}{2})*0+ กลุ่มของ 2 hex digits (non-capturing)
End$สิ้นสุดสตริง
InputValid?เหตุผล
0x1234567890✓10 hex digits (5 pairs), มี 0x prefix
123456789✗9 digits (ไม่ครบ 10, และเป็นเลขคี่)
123456789012✓12 hex digits (6 pairs)
sfdgdf35364✗มีตัวอักษรไม่ใช่ hex (s,f,d,g) และความยาวคี่
$@%#BV#*✗ไม่ใช่ hex digits

หมายเหตุ

  • \p{XDigit} = Hex digit [0-9a-fA-F] (Unicode property)
  • Lookahead (?=.{10,255}$) ตรวจสอบความยาวก่อน match จริง
  • โครงสร้าง \p{XDigit}{2}(?:\p{XDigit}{2})* บังคับให้เป็นคู่ๆ (even length)
  • 255 = arbitrary max length ปรับได้ตามต้องการ