簡體   English   中英

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

[英]Replace a special character with other special character within string

我想在字符串中替換一個特殊字符“with \\”。 我試過str = str.replaceAll(“\\”“,”\\\\\\“);但這不起作用。

第二個參數中缺少結束引號。 改成:

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

另請參見此示例

你必須通過加倍來逃避它:\\\\

代碼示例:

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

這給出了以下輸出:

\\terte\
||terte|

String.replaceAll()API

將給定替換的給定正則表達式匹配的此字符串的每個子字符串替換。

調用str.replaceAll(regex,repl)形式的此方法會產生與表達式完全相同的結果

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

請注意,替換字符串中的反斜杠()和美元符號($)可能導致結果與將其視為文字替換字符串時的結果不同; 見Matcher.replaceAll。 如果需要,使用Matcher.quoteReplacement(java.lang.String)來抑制這些字符的特殊含義。

順便說一句,這是重復的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM