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

Tách chuỗi theo chuỗi cố định (fixed delimiter) trong Java

Phương thức split(regex) nhận regex, không phải chuỗi cố định. Để tách theo chuỗi literal, cần escape regex meta-characters.

Vấn đề: split() nhận regex


"a.b.c".split(".");    // [] – vì "." khớp mọi ký tự
"a.b.c".split("\\.");  // ["a", "b", "c"] – escape
"a|b|c".split("|");    // ["a", "|", "b", "|", "c"] – "|" là OR
"a|b|c".split("\\|");  // ["a", "b", "c"]

Giải pháp: Pattern.quote() – Tự động escape


String delimiter = " to "; // chuỗi cố định
String[] parts = source.split(Pattern.quote(delimiter));
// An toàn cho mọi ký tự đặc biệt regex

Ví dụ: Tách nội dung file theo " to "


import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

public class SplitFixedString {
    public static void main(String[] args) throws IOException {
        String content = Files.readString(Paths.get("D:/sample.txt"));
        
        String delimiter = " to ";
        String[] parts = content.split(Pattern.quote(delimiter));
        
        System.out.println("Số phần: " + parts.length);
        for (int i = 0; i < parts.length; i++) {
            System.out.println("Part " + i + ": " + parts[i].trim());
        }
    }
}

Kết quả mẫu


Số phần: 4
Part 0: Tutorials Point originated from the idea that there exists a class of readers who respond better
Part 1: on-line content and prefer
Part 2: learn new skills at their own pace from the comforts of their drawing rooms.
Part 3: At Tutorials point we provide high quality learning-aids for free of cost.

Lưu ý

  • split() loại bỏ trailing empty strings mặc định. Dùng split(regex, -1) để giữ.
  • Pattern.quote() bọc toàn bộ chuỗi trong \\Q...\\E.
  • Java 12+: String.split(CharSequence) vẫn là regex – không có overload cho literal.

Alternatives

  • StringTokenizer – legacy, chỉ single-char delimiter
  • Scanner.useDelimiter(Pattern) – stream tokens
  • Apache Commons StringUtils.split() – có overload cho literal