在替换模式中使用组的捕获文本
import java.util.regex.Matcher; import java.util.regex.Pattern;/* from n o w j a v a . c o m - 时 代 Java*/ public class Main { public static void main(String[] args) { // Compile regular expression String patternStr = "\\((\\w+)\\)"; String replaceStr = "<$1>"; Pattern pattern = Pattern.compile(patternStr); // Replace all (\w+) with <$1> CharSequence inputStr = "a (b c) d (ef) g"; Matcher matcher = pattern.matcher(inputStr);