Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java regex tách chuỗi tại space và dấu câu


Regex khớp space và punctuation

[!._,'@?\\s]

Khớp: ! . , _ ' @ ? và whitespace (\s = space, tab, newline...)

Ví dụ 1: Đếm dấu câu/space

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("Số khớp: " + count); // 8
    }
}

Ví dụ 2: Tách từ (split)

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("Nhập chuỗi: ");
        String input = sc.nextLine();
        StringTokenizer str = new StringTokenizer(input, regex);
        while (str.hasMoreTokens()) {
            System.out.println(str.nextToken());
        }
    }
}
Nhập chuỗi: This is!a.sample text,with punctuation!marks@and_spaces
This
is
a
sample
text
with
punctuation
marks
and_spaces

Cách hiện đại (Java 8+)

// Dùng Pattern.splitAsStream
Pattern p = Pattern.compile("[!._,'@?\\s]+");
List words = p.splitAsStream(input)
    .filter(s -> !s.isEmpty())
    .collect(Collectors.toList());

Lưu ý

  • StringTokenizer legacy, nên dùng split() hoặc Pattern.splitAsStream().
  • Regex [!._,'@?\\s]+ (có +) gộp nhiều delimiter liên tiếp thành một.
  • Underscore _ trong ví dụ không bị tách vì không trong char class.