String patternStr = "\\((\\w+)\\)"; //這里對應的正則表達式 \((\w+)\) 兩個\\是java字符表示需要的轉義
String replaceStr = "|$1|";\\這里$1引用group,就是前邊表達式中的(\w+)部分,附注正則表達式中用()表示一個組,$1可以寫為\1,兩者都指代第一個group
Pattern pattern = Pattern.compile(patternStr);\\編譯,沒什么說的
// Replace all (\w+) with |$1|
CharSequence inputStr = "a (b c) d (ef) g";\\需要替換的字符串
Matcher matcher = pattern.matcher(inputStr);
String output = matcher.replaceAll(replaceStr);
// a (b c) d |ef| g
System.out.println(output);