The appendReplacement and appendTail

appendReplacement and appendTail are the methods that do the real work when you call replaceAll. Each time a match is found in the input, appendReplacement appends to the output all the text between the previous match and the current one, then it appends the replacement text. appendReplacement is also the method that processes the replacement text, converting $1, $2, etc. to the corresponding captured groups. When there are no more matches, appendTail appends whatever’s left of the input (whatever followed the last match).

You use appendReplacement and appendTail directly when you want to process the input in some other–or additional–manner than replaceAll does. For instance, if you want to use the matched text as a key to look up the replacement value in a table, you have to write your own replaceAll equivalent. Here’s an example I happened to have handy:

view plaincopy to clipboardprint?

Note: Text content in the code blocks is automatically word-wrapped
  1. import java.util.*;  
  2. import java.util.regex.*;  
  3.    
  4. class Test  
  5. {  
  6.   static Map props = new HashMap();  
  7.   static  
  8.   {  
  9.     props.put(“key1”“fox”);  
  10.     props.put(“key2”“dog”);  
  11.   }  
  12.    
  13.   public static void main(String[] args)  
  14.   {  
  15.     String input = “The quick brown ${key1} jumps over the lazy ${key2}.”;  
  16.    
  17.     Pattern p = Pattern.compile(“\\$\\{([^}]+)\\}”);  
  18.     Matcher m = p.matcher(input);  
  19.     StringBuffer sb = new StringBuffer();  
  20.     while (m.find())  
  21.     {  
  22.       m.appendReplacement(sb, “”);  
  23.       sb.append(props.get(m.group(1)));  
  24.     }  
  25.     m.appendTail(sb);  
  26.     System.out.println(sb.toString());  
  27.   }  
  28. }