appendReplacement
appendReplacement is a method in Java's regular expression API, provided by the class java.util.regex.Matcher. It is used to progressively build a new string by performing replacements for each match within an input sequence. The method appends to a given StringBuffer the portion of the input preceding the current match and the replacement text, with any backreferences in the replacement string expanded according to the current match. After appending, the internal position advances to the end of the current match, allowing subsequent calls to handle later matches.
- boolean appendReplacement(StringBuffer sb, String replacement)
- The replacement string can contain references to captured groups using $1, $2, etc., which are substituted
- The method returns true if there is another match in the region after the current one, and
- The input text is not modified; instead, the result is accumulated in the provided StringBuffer.
- Create a Matcher for the input text.
- Create a StringBuffer to hold the result.
- Iterate with while (matcher.find()) { matcher.appendReplacement(resultBuffer, replacement); }
- After the loop, call matcher.appendTail(resultBuffer) to append the remaining part of the input.
- The final string can be obtained from resultBuffer.toString().
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("order 123, item 45");
StringBuffer sb = new StringBuffer();
m.appendReplacement(sb, "NUMBER");
}
System.out.println(sb.toString());
- If the replacement string needs to be treated literally, use Matcher.quoteReplacement.
- This method is commonly paired with appendTail to assemble the full replaced string.