public String[] split(String regex) public String[] split(String regex, int limit)
無參版等同 split(regex, 0)。
| limit 值 | 行為 | 匹配次數 | 尾部空串處理 |
|---|---|---|---|
limit > 0 | 最多分割 limit 段,即應用模式 limit-1 次 | 最多 limit-1 次 | 保留 |
limit < 0 | 無限制分割,應用模式盡可能多次 | 無限 | 保留 |
limit = 0 | 無限制分割 | 無限 | 丟棄 |
String s = "boo:and:foo";
String[] r = s.split(":", 2);
// r = ["boo", "and:foo"] // 僅分割 1 次,剩餘部分保留原樣
String s = "boo:and:foo";
String[] r = s.split(":", -2);
// r = ["boo", "and", "foo"] // 全部分割,保留尾部空串(此處無)
String s = "boo:and:foo";
String[] r0 = s.split("o", 0); // 分割字元 'o'
String[] r1 = s.split("o", -2);
System.out.println(Arrays.toString(r0)); // [b, , :and:f] // 尾部空串被丟棄
System.out.println(Arrays.toString(r1)); // [b, , :and:f, , ] // 尾部空串保留
原始碼關鍵邏輯
// java.lang.String.split 核心片段 public String[] split(String regex, int limit) { return pattern.split(this, limit); } // java.util.regex.Pattern.split public String[] split(CharSequence input, int limit) { int index = 0; boolean matchLimited = limit > 0; ArrayListmatchList = new ArrayList<>(); Matcher m = matcher(input); while (m.find()) { if (matchLimited && matchList.size() == limit - 1) break; // 達到上限停止 matchList.add(input.subSequence(index, m.start()).toString()); index = m.end(); } matchList.add(input.subSequence(index, input.length()).toString()); // 最後一段 // limit == 0 時移除尾部空串 if (limit == 0) { int i = matchList.size(); while (i > 0 && matchList.get(i - 1).length() == 0) i--; matchList.subList(i, matchList.size()).clear(); } return matchList.toArray(new String[0]); } 常見坑點避雷
- 正則元字元需轉義:
split(".")分割任意字元,需split("\\.")或split(Pattern.quote("."))。- 效能陷阱:大字串頻繁
split創建大量陣列與字串物件,考慮StringTokenizer、Scanner或手寫解析。limit=0丟棄尾部空串 導致 CSV 解析漏列,CSV 必須用limit=-1。- Java 8+
Pattern.splitAsStream返回Stream,配合limit(n)可流式處理,避免全量陣列。