Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用转义字符替换字符串中的模式使用replaceAll失败_Java_String_Replace_Replaceall - Fatal编程技术网

Java 使用转义字符替换字符串中的模式使用replaceAll失败

Java 使用转义字符替换字符串中的模式使用replaceAll失败,java,string,replace,replaceall,Java,String,Replace,Replaceall,我有一个用例,我想替换html字符串中的一些值,因此我需要为此执行replaceAll,但这不起作用,尽管replace工作正常,但我的代码如下: String str = "<style type=\"text/css\">#include(\"Invoice_Service_Tax.css\")</style>"; String pattern = "#include(\"Invoice_Service_Tax.css\")"; System

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

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

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

正则表达式的问题是
是用于分组的特殊字符,因此需要对其进行转义


\\\\\(\“发票\服务\税.css\”\)
应该与
replaceAll
一起使用
String.replace
String.replaceAll
之间的关键区别在于
String的第一个参数。replace
String literal
,但对于
String.replaceAll
来说,它是一个
regex
。它对此有很好的解释。因此如果t下面是要替换的字符串中的特殊字符,如
\
$
,您将再次看到不同的行为,如:

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\""
}
publicstaticvoidmain(字符串[]args){
字符串str=“#包含\“发票\服务\税\.css\”;
字符串模式=“#包含\“发票\服务\税\.css\”;
System.out.println(str.replace(pattern,“some value”);//有效
System.out.println(str.replaceAll(pattern,“some value”);//不起作用,模式应为:“include\”发票\服务\税务\\\\\.css\”
}
"#include(\\\"Invoice_Service_Tax.css\\\")"
"#include(Invoice_Service_Tax.css)"
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\""
}