Using the Captured Text of a Group within a Replacement Pattern
Just as it is possible to use the value of a group within the same
pattern (see Using the Captured Text of a Group within a Pattern), it is also
possible to use a group value in the replacement pattern. Instead of
a backslash, the form of the reference is $n where n is a group
number starting from 0 (see Capturing Text in a Group in a Regular Expression for more
information on groups).
// 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);
String output = matcher.replaceAll(replaceStr);
// a (b c) d <ef> g
Post a comment