Matcher.appendReplacement with literal text

后端 未结 3 945
没有蜡笔的小新
没有蜡笔的小新 2021-01-08 00:29

I am using Matcher.appendReplacement() and it worked great until my replacement string had a $2 in it:

Note that backslashes ( \\ ) and dollar signs

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-08 01:06

    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));
    

提交回复
热议问题