Character class \p{Digit} ใช้ match decimal digits คือ ตัวเลข 0 ถึง 9 เท่านั้น
- Match:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 - เทียบเท่ากับ
[0-9]และ\d(ใน Java \d = \p{Digit} โดย default) - รองรับ Unicode decimal digits ด้วย (เช่น ๐-๙, ٠-٩, ०-९) ถ้าใช้
Pattern.UNICODE_CHARACTER_CLASS
ตัวอย่างที่ 1: นับจำนวน digits
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DigitsExample {
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{Digit}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of digits: " + count);
}
}
Output 1
Enter a string sample text 22 37 48 84 Number of digits: 8
Output 2
Enter a string Welcome to tutorilspoint Number of digits: 0
ตัวอย่างที่ 2: หาสตริงที่ประกอบด้วย digits เท่านั้น
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
// Regex: เริ่มจบด้วย digits เท่านั้น
String regex = "^\\p{Digit}+$";
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 only digits:");
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: hello 1234 243test ##$$@ 222356 Strings with only digits: 1234 222356
ความแตกต่าง \p{Digit} vs \d vs \p{XDigit}
| Pattern | Match | หมายเหตุ |
|---|---|---|
\p{Digit} |
Decimal digits (0-9 + Unicode digits) | POSIX standard, Unicode-aware |
\d |
Decimal digits (0-9 + Unicode digits) | Shorthand, เทียบเท่า \p{Digit} ใน Java |
\p{XDigit} |
Hex digits (0-9, a-f, A-F) | กว้างกว่า รวม A-F |
[0-9] |
ASCII digits only (0-9) | เร็วที่สุด, ไม่รองรับ Unicode digits |
กรณีใช้งานทั่วไป
- Validate numeric input:
^\\p{Digit}+$ - Extract numbers:
\\p{Digit}+(หาตัวเลขต่อเนื่อง) - Validate PIN/OTP:
^\\p{Digit}{4,6}$ - Credit card number:
^\\p{Digit}{13,16}$ - Thai digit support:
\\p{Digit}match ๐-๙ ได้ (ต้องมี Unicode flag)
ตัวอย่างเพิ่มเติม: Extract ทุกกลุ่มตัวเลข
String text = "Order 12345 placed on 2024-01-15, total $99.99";
Pattern p = Pattern.compile("\\p{Digit}+");
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group()); // 12345, 2024, 01, 15, 99, 99
}