The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.regex  [26 examples] > Groups  [5 examples]

e440. 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 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

 Related Examples
e436. Capturing Text in a Group in a Regular Expression
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

See also: Flags    Lines    Paragraphs    Searching and Replacing    Tokenizing   


© 2002 Addison-Wesley.