Regex [!._,'@?\\s] จับคู่ punctuation marks และ whitespace ทั้งหมด
ตัวอย่าง 1: นับ punctuation และ space
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "This is!a.sample\"text,with punctuation!marks";
Pattern p = Pattern.compile("[!._,'@?\\s]");
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
}
System.out.println("Number of matches: " + count);
}
}
ผลลัพธ์
Number of matches: 8
ตัวอย่าง 2: แยกสตริงด้วย StringTokenizer
เมธอด split() ของ String แยกตาม regex คืนอาร์เรย์ tokens (ข้อความระหว่างสอง match)
ใช้ StringTokenizer แยกที่ space และ punctuation:
import java.util.Scanner;
import java.util.StringTokenizer;
public class RegExample {
public static void main(String args[]) {
String regex = "[!._,'@? ]";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = sc.nextLine();
StringTokenizer str = new StringTokenizer(input, regex);
while (str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}
ผลลัพธ์
Enter a string: This is!a.sample text,with punctuation!marks@and_spaces
This
is
a
sample
text
with
punctuation
marks
and_spaces
อธิบาย
- Regex
[!._,'@?\\s]ใน Pattern: จับคู่ ! . _ , ' @ ? และ whitespace (\s = space, tab, newline) - Regex
[!._,'@? ]ใน StringTokenizer: จับคู่ ! . _ , ' @ ? และ space (ไม่รวม tab, newline) StringTokenizerแยก tokens โดยใช้ chars ใน regex เป็น delimiters- Note:
and_spacesคงอยู่เพราะ_(underscore) ไม่อยู่ใน delimiter set
เปรียบเทียบ split() vs StringTokenizer
| คุณสมบัติ | String.split(regex) | StringTokenizer |
|---|---|---|
| Regex support | เต็มรูปแบบ | เฉพาะ character set (ไม่ใช่ regex จริง) |
| คืนค่า | String[] | Iterator (hasMoreTokens/nextToken) |
| Empty tokens | เก็บไว้ (leading/trailing/consecutive) | ข้าม empty tokens |
| Performance | ช้ากว่า (compile regex) | เร็วกว่า (simple char matching) |
| Deprecated | ไม่ | Legacy (แนะนำใช้ split หรือ Scanner) |
แนะนำ: ใช้ split() แบบสมัยใหม่
// แยกที่ non-word characters (punctuation + whitespace)
String[] tokens = input.split("[\\p{Punct}\\s]+");
// หรือเฉพาะที่ต้องการ
String[] tokens = input.split("[!.,;:'@?\\s]+");