模式使用replaceAll替换带有转义字符的字符串

时间:2017-04-01 07:49:02

标签: java string replace 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>

对于我的用例,我只需要替换所有,我尝试使用以下模式,但没有帮助:

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

2 个答案:

答案 0 :(得分:3)

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

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

#include\\(\"Invoice_Service_Tax.css\"\\)应与replaceAll

一起使用

答案 1 :(得分:1)

String.replaceString.replaceAll之间的主要区别在于String.replace的第一个参数是string literal,但对于String.replaceAll,它是regex }。 java 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\""
}
相关问题