Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Java Regex: แยกสตริงที่ Space และ Punctuation ทุกตัว

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]+");