2017-04-01 102 views
2

我有一个用例,我想在html字符串中替换一些值,所以我需要为replaceAll做这件事,但那不工作,虽然替换工作正常,这里是我的代码:模式替换字符串中的转义字符失败与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)" 

回答

3

替换不寻找特殊字符,只是一个文字替换,而replaceAll使用正则表达式,所以有一些特殊字符。

正则表达式的问题是,(是一个特殊的字符分组,所以你需要逃避它。

#include\\(\"Invoice_Service_Tax.css\"\\)应与工作中的replaceAll

+0

这个工作对我来说:) – user2098324

1

String.replaceString.replaceAll之间的关键区别在于String.replace第一个参数是​​,但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\"" 
}