字符串 2(10)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0),需提取所有括號內的數字(如 10、2、0 等),要求通用性強。
使用正則表達式匹配括號內容:
String str = "2(10)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)";
Pattern pattern = Pattern.compile("\\((\\d+)\\)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1)); // 輸出括號內的數字
}
若需處理嵌套括號,可用棧解析或遞歸下降;但題目示例中括號內均為純數字,上述正則足夠。