簡體   English   中英

如何檢查和替換java中的String中包含的特殊字符(\\)?

[英]How to check and replace special character(\) contain in a String in java?

我有一個String str=p2\\7\\2010我想檢查並替換str.contains("\\")然后將其替換為此("\\\\\\\\")而不是\\ 我無法用Java做到這一點請你付出一點努力。

使用String.replace()

if (str.contains("\\")) {
    str = str.replace("\\", "\\\\");
}

您也可以使用String.replaceAll() ,但它使用正則表達式,因此在這種簡單的情況下速度較慢。

更新:

String.replace()實現也基於正則表達式,但是在Pattern.LITERAL模式下編譯。

str.contains("\\"")匹配具有”in“的字符串。

你可能想要的是str.replaceAll("\\\\", "\\\\\\\\")

另外; 檢查它是否包含\\你需要str.contains("\\\\") ,因為\\是一個特殊字符,它必須被轉義。

試試這個,

String newString = oldString.replace("/", "//");

或嘗試模式方法,

Pattern pattern = Pattern.compile("/"); 
Matcher matcher = pattern.matcher("abc/xyz"); 
String output = matcher.replaceAll("//"); 

暫無
暫無

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

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