![]() |
The Java Developers Almanac 1.4 |
|
e440. Using the Captured Text of a Group within a Replacement PatternJust as it is possible to use the value of a group within the same pattern (see e439 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 e436 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
e437. Getting the Indices of a Matching Group in a Regular Expression e438. Using a Non-Capturing Group in a Regular Expression e439. Using the Captured Text of a Group within a Pattern
© 2002 Addison-Wesley. |