Java-Rearranging Captured Group

Rearranging Captured Group

The appendReplacement() method has special provision for recognizing references to capturing groups in the replacement text string. If $n, where n is an integer, appears in the replacement string, it is interpreted as the text corresponding to group n. You can therefore replace the text matched to a complete pattern by any sequence of your choosing of the subsequences corresponding to the capturing groups in the pattern.

Program



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("(\\d{4})(\\d{2})(\\d{2})");
        Matcher mat = pat.matcher("Date Of Birth : 19901204 : I AM 26");
        
        StringBuffer newstr = new StringBuffer();
        
        while(mat.find())
        { 
            mat.appendReplacement(newstr,"$3/$2/$1");
        }
        mat.appendTail(newstr);
        System.out.println(newstr);
    }
}

Leave a Comment