Pattern p = Pattern.compile("<char>(.*?)</char>");
Matcher m = p.matcher(input);
String[] arr = new String[m.groupCount()]; // 錯誤:groupCount() 回傳 1
groupCount() 返回**正則模式中捕獲組(括號對)的數量**,上例只有 (.*?) 一組,故回傳 1,與實際匹配到幾個 <char>...</char> 無關。
List results = new ArrayList<>();
while (m.find()) {
results.add(m.group(1)); // group(1) 取第一個捕獲組內容
}
String[] arr = results.toArray(new String[0]);
m.find() 逐個尋找下一個匹配。m.group(0) 為整個匹配字串(含 <char> 標籤),m.group(1) 為第一個括號內內容。(?:...) 非捕獲組,groupCount() 不會計入。replaceAll 可直接替換所有匹配,無需手動迭代。