2012-03-01 195 views
0

我想用字符串替換特殊字符「with \」。 我試圖海峽= str.replaceAll( 「\」」, 「\\\」); 但是,這並不工作用字符串中的其他特殊字符替換特殊字符

+0

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

回答

0

你必須加倍它逃脫\:\\

代碼示例:

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

這給出以下輸出:

\\terte\ 
||terte| 
0

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

2

收盤報價中缺少第二個參數。更改爲:

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

另請參閱this example