Character class \p{ASCII} ใช้ match ASCII characters คือ ตัวอักษรในช่วง \x00-\x7F (0-127 decimal) ประกอบด้วย:
- Control characters:
\x00-\x1F(0-31) และ\x7F(127 DEL) - Printable ASCII:
\x20-\x7E(32-126) - space, punctuation, digits, letters, symbols
รวมทั้ง printable และ non-printable ASCII characters
ตัวอย่าง: นับจำนวน ASCII characters
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String input = sc.nextLine();
// Regex: ASCII character (แต่ตัวอย่างต้นฉบับมี bug - ใช้ ^ ผิด)
String regex = "\\p{ASCII}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of ASCII characters in the given string: " + count);
}
}
Output
Enter a string why do we fall Number of ASCII characters in the given string: 14
หมายเหตุ: ตัวอย่างต้นฉบับ Output แสดง 1 ซึ่งผิด - "why do we fall" มี 14 ASCII characters (รวม space)
การใช้งานจริง: ตรวจสอบ/ลบ non-ASCII characters
ใช้ [^\\p{ASCII}] (negation) เพื่อ match non-ASCII characters
ตัวอย่าง: ลบ non-ASCII characters
import java.util.Scanner;
public class RemoveNonAscii {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input data:");
String input = sc.nextLine();
// Match non-ASCII characters
String regex = "[^\\p{ASCII}]";
String result = input.replaceAll(regex, "");
System.out.println("Result (ASCII only): " + result);
}
}
Output
Enter input data: whÿ do we fall Result (ASCII only): wh do we fall
คำอธิบาย: ÿ (U+00FF) ไม่ใช่ ASCII ถูกลบออก
ความแตกต่าง \p{ASCII} vs \p{Print} vs \p{Graph}
| Class | Range | รวม Control Chars? | รวม Non-ASCII? |
|---|---|---|---|
\p{ASCII} |
\x00-\x7F | ใช่ | ไม่ |
\p{Print} |
Printable chars (Unicode) | ไม่ (ยกเว้น space) | ใช่ (Unicode printable) |
\p{Graph} |
Visible chars (Unicode) | ไม่ | ใช่ (Unicode visible) |
[\x20-\x7E] |
Printable ASCII only | ไม่ | ไม่ |
กรณีใช้งานทั่วไป
- Validate ASCII-only input:
^\\p{ASCII}*$หรือ^[\\x00-\\x7F]*$ - Detect non-ASCII:
[^\\p{ASCII}] - Sanitize สำหรับ legacy systems ที่รองรับแค่ ASCII
- Check file encoding compatibility
- Email local-part validation (RFC 5322 อนุญาต ASCII เท่านั้นในบางส่วน)
หมายเหตุ
\p{ASCII}ไม่ได้แปลว่า "printable ASCII" - มันรวม control characters ด้วย- หากต้องการ printable ASCII เท่านั้น ใช้
[\\x20-\\x7E]หรือ[ -~] - ใน Java ใช้
StandardCharsets.US_ASCIIสำหรับ encoding/decoding จริงๆ