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

Posix Character Class \p{XDigit} ใน Java Regex

Character class \p{XDigit} ใช้ match hexadecimal digits คือ ตัวอักษรที่ใช้ในระบบเลขฐาน 16 ประกอบด้วย:

  • 0-9 - ตัวเลข 0 ถึง 9
  • a-f - ตัวอักษรพิมพ์เล็ก a ถึง f
  • A-F - ตัวอักษรพิมพ์ใหญ่ A ถึง F

เทียบเท่ากับ [0-9a-fA-F] หรือ [0-9a-fA-F]

ตัวอย่างที่ 1: นับจำนวน hexadecimal characters

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpaceCharacters {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string:");
        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("Number of hexadecimal characters: " + count);
    }
}

Output

Enter a string
Bb12\tc!
Number of hexadecimal characters: 5

คำอธิบาย: B, b, 1, 2, c เป็น hex digits (tab และ ! ไม่ใช่)

ตัวอย่างที่ 2: หาสตริงที่มี hexadecimal characters อยู่

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        // Regex: มี hex digit อย่างน้อย 1 ตัว
        String regex = "^.*\\p{XDigit}.*$";

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter 5 input strings:");
        String[] input = new String[5];
        for (int i = 0; i < 5; i++) {
            input[i] = sc.nextLine();
        }

        Pattern p = Pattern.compile(regex);
        System.out.println("Strings with hexadecimal characters:");
        for (int i = 0; i < 5; i++) {
            Matcher m = p.matcher(input[i]);
            if (m.matches()) {
                System.out.println(m.group());
            }
        }
    }
}

Output

Enter 5 input strings:
sample
123
xyz
@##
DEF01
Strings with hexadecimal characters:
sample
123
DEF01

คำอธิบาย: "sample" มี a,b,c,d,e,f ที่เป็น hex, "123" เป็นตัวเลข, "DEF01" มี D,E,F,0,1

กรณีใช้งานทั่วไป

  • Validate hex color codes: ^#\p{XDigit}{6}$ หรือ ^#\p{XDigit}{3}$
  • Parse hex numbers: 0x\p{XDigit}+
  • Validate MAC address: ^(\p{XDigit}{2}:){5}\p{XDigit}{2}$
  • Check SHA/MD5 hashes: ^\p{XDigit}{32}$ (MD5), ^\p{XDigit}{40}$ (SHA-1), ^\p{XDigit}{64}$ (SHA-256)

หมายเหตุ

  • \p{XDigit} รองรับ Unicode hex digits ด้วย (แต่โดยปกติใช้ ASCII range)
  • สำหรับ ASCII เท่านั้น ใช้ [0-9a-fA-F] จะชัดเจนและเร็วกว่าเล็กน้อย