The replacement string can contain references to the groups in the pattern: $n is replaced with the nth group, and ${name} is replaced with the group that has the given name. Use \\$ to include a $ character in the replacement text.

If you have a string that may contain $ and \, and you don’t want them to be interpreted as group replacements, call matcher.replaceAll(Matcher.quoteReplacement(String str)).


Program Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
    public static void main(String[] args) {
        Pattern pat = Pattern.compile("AAA(BBB)(CCC)");
        Matcher mat = pat.matcher("AAABBBCCCXXX");
        String str = mat.replaceAll(Matcher.quoteReplacement("$1 Android $2"));

Leave a Comment