Matcher.appendReplacement with literal text

后端 未结 3 946
没有蜡笔的小新
没有蜡笔的小新 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 00:59

    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 chars. 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.]

    0 讨论(0)
  • 2021-01-08 01:00

    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.

    0 讨论(0)
  • 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));
    
    0 讨论(0)
提交回复
热议问题