更新:
从 Java 9 开始,我们可以使用Matcher#replaceAll(Function<MatchResult,String> replacer)like
String result = Pattern.compile("yourRegex")
                       .matcher(yourString)
                       .replaceAll(match -> yourMethod(match.group()));
                                         // ^^^- or generate replacement directly 
                                         // like `match.group().toUpperCase()`
在 Java 9 之前
您可以使用Matcher#appendReplacement和Matcher#appendTail。
appendReplacement会做两件事:
- 它将添加到当前匹配和前一个匹配之间的选定缓冲区文本(或第一个匹配的字符串开头),
 
- 之后,它还将为当前匹配添加替换(可以基于它)。
 
appendTail将添加到当前匹配之后放置的缓冲区文本。
Pattern p = Pattern.compile("yourRegex");
Matcher m = p.matcher(yourString);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, yourMethod(m.group()));
}
m.appendTail(sb);
String result = sb.toString();