public String[] split(String regex) 參數是正則表達式,非純字串。特殊字元需轉義,否則產生非預期結果。
| 分隔符 | 錯誤寫法 | 正確寫法 | 說明 |
|---|---|---|---|
| 點號 (.) | split(".") | split("\\.") | 正則中 . 代表任意字元 |
| 管線 (|) | split("|") | split("\\|") | 正則中 | 代表或邏輯 |
| 星號 (*) | split("*") | split("\\*") | 正則中 * 代表零或多次 |
| 加號 (+) | split("+") | split("\\+") | 正則中 + 代表一次或多次 |
| 反斜線 (\) | split("\") | split("\\\\") | 需雙重轉義:Java 字串 + 正則 |
| 問號 (?) | split("?") | split("\\?") | 正則中 ? 代表零或一次 |
| 括號 ()[]{} | split("(") | split("\\(") | 正則分組/字元類別符號 |
| 插入符 (^) | split("^") | split("\\^") | 正則開頭錨點 |
| 美元符 ($) | split("$") | split("\\$") | 正則結尾錨點 |
使用正則 | 運算子實現多重分隔:
String sql = "acount=? and uu=? or n=?";
// 同時以 and、or 分割
String[] parts = sql.split("and|or");
// 結果:["acount=?", " uu=?", " n=?"]
public class SplitDemo {
public static void main(String[] args) {
// 1. 管線分割
testSplit("aaa|bbb|ccc", "\\|");
// 2. 星號分割
testSplit("aaa*bbb*ccc", "\\*");
// 3. 多重分隔符
String sql = "id=1 and name='test' or status=1";
String[] tokens = sql.split("and|or");
System.out.println("多重分割結果:" + Arrays.toString(tokens));
// 4. 反斜線分割
testSplit("aaa\\bbb\\ccc", "\\\\\\\\"); // Java: \\\\ -> 正則: \\\\ -> 字面: \\
}
static void testSplit(String input, String regex) {
String[] result = input.split(regex);
System.out.printf("輸入:%s | 正則:%s | 結果:%s%n",
input, regex, Arrays.toString(result));
}
}
split("(?=\\|)|(?<=\\|)")split(regex, limit),limit > 0 最多分割 limit-1 次Arrays.stream(arr).filter(s -> !s.isEmpty()).toArray(String[]::new)Pattern.compile(regex) 重複使用| 錯誤現象 | 原因 | 解決方案 |
|---|---|---|
| PatternSyntaxException | 未轉義特殊字元 (*, +, ? 等) | 加上雙反斜線轉義 |
| 分割結果為空陣列 | 分隔符為開頭/結尾字元 | 檢查字串內容或使用 limit 參數 |
| 分割出多餘空字串 | 連續分隔符或首尾分隔符 | 後處理過濾空字串 |
| 中文字元分割異常 | 正則預設不支援 Unicode 類別 | 使用 \\p{IsHan} 或指定字元類別 |