用字符串中的其他特殊字符替换特殊字符

问题描述:

我想用字符串替换特殊字符“with \”。 我试图海峡= str.replaceAll( “\””, “\\\”); 但是,这并不工作用字符串中的其他特殊字符替换特殊字符

+0

[String.replaceAll反斜杠问题](http://stackoverflow.com/questions/1701839/backslash-problem-with-string-replaceall) – oers 2012-03-01 08:06:33

你必须加倍它逃脱\:\\

代码示例:

String tt = "\\\\terte\\"; 
System.out.println(tt); 
System.out.println(tt.replaceAll("\\\\", "|")); 

这给出以下输出:

\\terte\ 
||terte| 

String.replaceAll() API

将此字符串的每个子字符串替换为给定替换的匹配给定的常规 表达式。

形式str.replaceAll的这种方法(正则表达式,REPL) 产生完全相同的结果作为表达式的调用

Pattern.compile(regex).matcher(str).replaceAll(repl) 

注意反斜杠()和美元符号($)在更换 字符串可能会导致结果与将 视为字面替换字符串时的结果不同;看Matcher.replaceAll。如果需要,可使用 Matcher.quoteReplacement(java.lang.String)来抑制这些字符的特殊含义 。

Btw, it is duplicated question.

+1

您应该始终指向最新的api。您指向1.4.2 – tom 2012-03-01 07:59:21

+1

并且重复的链接仅指向api:D – oers 2012-03-01 08:00:56

收盘报价中缺少第二个参数。更改为:

str = str.replaceAll("\"","\\\\\""); 

另请参阅this example