ใช้ split("\\W+") แยกคำด้วย Non-Word Characters แล้วรวมกลับ (Regex \\W = Non-Word Character = ไม่ใช่ [a-zA-Z0-9_])
ตัวอย่างโค้ด
import java.util.Scanner;
public class RemoveNonAlphabetic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter string: ");
String input = sc.nextLine();
// แยกด้วย Non-Word Characters (\W+ = 1 หรือมากกว่า Non-word chars)
String[] words = input.split("\\W+");
// รวมกลับเป็น String เดียว
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(word);
}
System.out.println("Result: " + result.toString());
}
}
ผลลัพธ์
Enter string: Krishna ^% Kasyap*@# Result: KrishnaKasyap
คำอธิบาย Regex
\\W= Non-Word Character (เทียบเท่า[^a-zA-Z0-9_])+= หนึ่งตัวขึ้นไป (Group ติดกันเป็น Delimiter เดียว)split("\\W+")= ตัดที่ Non-Word Char ทุกชนิด (Space, Punctuation, Symbol, Underscore)
ทางเลือก: ใช้ replaceAll() (ตรงไปตรงมา)
// ลบทุกอย่างที่ไม่ใช่ตัวอักษรภาษาอังกฤษ (A-Z, a-z)
String result = input.replaceAll("[^a-zA-Z]", "");
// หรือรองรับ Unicode (Thai, etc.)
String resultUnicode = input.replaceAll("[^\\p{L}]", ""); // \\p{L} = Unicode Letter
ตัวอย่าง replaceAll
String input = "Hello, World! 123 สวัสดี";
System.out.println(input.replaceAll("[^a-zA-Z]", "")); // HelloWorld
System.out.println(input.replaceAll("[^\\p{L}]", "")); // HelloWorldสวัสดี
สรุป
- split + join - เข้าใจง่าย เหมาะสำหรับเก็บคำแยกกัน
- replaceAll("[^a-zA-Z]", "") - เร็ว กระชับ เหมาะสำหรับ English Only
- replaceAll("[^\\p{L}]", "") - รองรับ Unicode/Thai ได้เต็มที่