模式替换字符串中的转义字符因 replaceAll 而失败

Pattern Replacing in string with escaped characters failing with replaceAll

我有一个用例,我想替换 html 字符串中的一些值,所以我需要为此执行 replaceAll,但这不起作用,尽管替换工作正常,这是我的代码:

    String str  = "<style type=\"text/css\">#include(\"Invoice_Service_Tax.css\")</style>";
    String pattern = "#include(\"Invoice_Service_Tax.css\")";
    System.out.println(str.replace(pattern, "some-value"));
    System.out.println(str.replaceAll(pattern, "some-value"));

输出为:

<style type="text/css">some-value</style>
<style type="text/css">#include("Invoice_Service_Tax.css")</style>

对于我的用例,我只需要执行 replaceAll,我也尝试了以下模式但没有帮助:

"#include(\\"Invoice_Service_Tax.css\\")"
"#include(Invoice_Service_Tax.css)"

替换不查找特殊字符,只是文字替换,而 replaceAll 使用正则表达式,因此有一些特殊字符。

正则表达式的问题在于 ( 是用于分组的特殊字符,因此您需要将其转义。

#include\(\"Invoice_Service_Tax.css\"\) 应该可以与您的 replaceAll

一起使用

String.replaceString.replaceAll的主要区别在于String.replace的第一个参数是string literal,而String.replaceAll的第一个参数是regexjava doc of those two methods 对此有很好的解释。因此,如果要替换的字符串中有 \$ 等特殊字符,您将再次看到不同的行为,例如:

public static void main(String[] args) {
    String str  = "<style type=\"text/css\">#include\"Invoice_Service_Tax\.css\"</style>";
    String pattern = "#include\"Invoice_Service_Tax\.css\"";
    System.out.println(str.replace(pattern, "some-value")); // works
    System.out.println(str.replaceAll(pattern, "some-value")); // not works, pattern should be: "#include\"Invoice_Service_Tax\\.css\""
}