I am using Matcher.appendReplacement() and it worked great until my replacement string had a $2 in it:
Note that backslashes ( \\ ) and dollar signs
Use Matcher.quoteReplacement on the replacement string.
Unfortunately "ease of use" in this case conflicts with strong typing. [Explanation: An object of Java static type java.lang.String
is any immutable sequence of char
s. It doesn't tell you the format of that raw data. In this scenario we have text probably meaningful to the user, text encoded in a mini-language for replacement and text encoded in a mini-language for the pattern. The Java type system has no way of distinguishing these (although you can do fun things with annotation-based type checkers, often to avoid XSS or SQL/command injection vulnerabilities). For the pattern mini-language you can to a form of conversion with Pattern.compile
although that is a specific use and most APIs methods ignore it (for ease of use). An equivalent ReplacementText.compile
could be written. Further, you could ignore the mini-languages and go for libraries as "DSLs". But all this doesn't help casual ease of use.]
Here's another option:
matcher.appendReplacement(stringbuffer, "");
stringbuffer.append(replacement);
appendReplacement()
handles the job of copying over the text between the matches, then StringBuffer#append()
adds your replacement text sans adulterations. This is especially handy if you're generating the replacement text dynamically, as in Elliott Hughes' Rewriter.
I got it to work with the following, but I like Tom Hawtin's solution better :-)
private static Pattern escapePattern = Pattern.compile("\\$|\\\\");
replacement = escapePattern.matcher(replacement).replaceAll("\\\\$0");
matcher.appendReplacement(stringbuffer, replacement);
Tom's solution:
matcher.appendReplacement(stringbuffer, Matcher.quoteReplacement(replacement));