Character class \p{Alpha} ใช้ match alphabetic characters คือ ตัวอักษรทั้งพิมพ์ใหญ่และพิมพ์เล็ก
- Match:
a-z,A-Zและ Unicode letters ทุกภาษา (ไทย, จีน, ญี่ปุ่น, โกรเมน, คิริลลิก, อรบิก, ฮีบรู, ไทย, เดเวนาคารี, ฯลฯ) - ไม่ Match: ตัวเลข (0-9), Punctuation, Whitespace, Symbols
- เทียบเท่า:
[a-zA-Z](ASCII only) |\p{L}(Unicode Letter - กว้างกว่า)
ตัวอย่างที่ 1: หาสตริงที่ประกอบด้วย alphabets เท่านั้น
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
// Regex: เริ่มจบด้วย alphabets เท่านั้น
String regex = "^\\p{Alpha}+$";
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 alphabets:");
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 sample 243test ##$$@ 222356 Strings with alphabets: hello sample
ตัวอย่างที่ 2: นับจำนวน alphabetic 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();
String regex = "\\p{Alpha}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of alphabetic characters: " + count);
}
}
Output
Enter a string sample text Number of alphabetic characters: 10
คำอธิบาย: s,a,m,p,l,e,t,e,x,t = 10 ตัว (space ไม่นับ)
ความแตกต่าง \p{Alpha} vs \p{Alnum} vs \p{Lower} vs \p{Upper} vs \p{L}
| Class | Match | หมายเหตุ |
|---|---|---|
\p{Alpha} |
Letters (Upper + Lower) | POSIX name = Alphabetic |
\p{Alnum} |
Alpha + Digits | Alpha + Numeric |
\p{Lower} |
Lowercase letters only | POSIX: \p{Ll} |
\p{Upper} |
Uppercase letters only | POSIX: \p{Lu} |
\p{L} |
All Unicode Letters | Unicode General Category: Letter (กว้างกว่า Alpha) |
\p{javaLowerCase} |
Java isLowerCase() | Java-specific, รวม title case บางตัว |
\p{javaUpperCase} |
Java isUpperCase() | Java-specific |
กรณีใช้งานทั่วไป
- Validate name:
^\\p{Alpha}+( [\\p{Alpha}]+)*$(ชื่อ-นามสกุล ภาษาอังกฤษ) - Validate Thai name:
^[\\p{Alpha}\\s]+$(รองรับไทยเพราะ \p{Alpha} ครอบคลุมไทย) - Extract words:
\\p{Alpha}+ - Check if string contains only letters:
str.matches("^\\p{Alpha}+$") - Remove non-letters:
str.replaceAll("[^\\p{Alpha}]", "")
หมายเหตุสำคัญ
\p{Alpha}ใน Java = POSIX[:alpha:]= UnicodeGeneral_Category=Letterแต่ ไม่รวม Letter Numbers (Nl) และ Mark (M)\p{L}(หรือ\p{Letter}) กว้างกว่า ครอบคลุม Lu, Ll, Lt, Lm, Lo, Nl- สำหรับ ASCII เท่านั้น ใช้
[a-zA-Z]จะมีประสิทธิภาพดีกว่า