如何替换所有子字符串?

How to replace all substrings?

我想将任何 String 对象的括号内的所有文本替换为大写字母。例如,如果文本是 - Hi (abc), how (a)re (You)?" ,输出应该是 - Hi ABC, how Are YOU? 。我尝试使用 StringUtils.SubstringBetween(),但它只替换了 () 之间的第一个子字符串。 使用 regex,我想 group() 方法需要对此类子字符串进行计数。正确的方向是什么?

因为 Java 9 我们可以使用 Matcher.replaceAll​(Function<MatchResult,String> replacer)

String str = "Hi (abc), how (a)re (You)?";

Pattern p = Pattern.compile("\((.*?)\)"); //matches parenthesis and places 
                                            //content between them in group 1
String replaced = p.matcher(str)
        .replaceAll(match -> match.group(1).toUpperCase()); //replace each match with
                                            //content of its group 1 in its upper case 

System.out.println(replaced);

输出:Hi ABC, how Are YOU?