我想對字符串執行以下操作。在Java中轉義*字符
if (combatLog.contains("//*name//*")) {
combatLog.replaceAll("//*name//*",glad.target.name);
}
斜槓是我試圖逃避*,因爲它沒有它們就無法工作。我也嘗試了一個斜線,並在包含或單獨替換所有的斜槓上。由於
我想對字符串執行以下操作。在Java中轉義*字符
if (combatLog.contains("//*name//*")) {
combatLog.replaceAll("//*name//*",glad.target.name);
}
斜槓是我試圖逃避*,因爲它沒有它們就無法工作。我也嘗試了一個斜線,並在包含或單獨替換所有的斜槓上。由於
不要忘記不變性的字符串,並重新分配新創建的字符串。此外,如果您的if
塊不包含任何更多代碼,則根本不需要if
檢查。
你有3種選擇:
if (combatLog.contains("*name*")) { // don't escape in contains()
combatLog = combatLog.replaceAll("\\*name\\*", replacement);// correct escape
}
// another regex based solution
if (combatLog.contains("*name*")) {
combatLog = combatLog.replaceAll("[*]name[*]", replacement);// character class
}
或沒有正則表達式
if (combatLog.contains("*name*")) {
combatLog = combatLog.replace("*name*", replacement);// literal string
}
您使用正斜槓使用反斜槓:\
逃脫字符
[編輯] 也爲slaks說你需要使用哪個replace()
接受一個字符串作爲輸入,而不是一個正則表達式。
您正在使用正斜槓。反斜槓是轉義字符。此外,除非字符串正在用於正則表達式或類似的東西,否則不需要轉義*
或/
,如果這就是你想要逃避的東西。
如果combatLog是一個字符串,它的包含方法只檢查字符序列。如果您要查找字符串中的*name*
,您只需撥打combatLog.contains("*name*")
即可。
replaceAll()
(反直覺)需要一個正則表達式,而不是一個字符串。
爲了逃避正則表達式的字符,你需要一個雙 - 回斜槓(加倍以從字符串文字中反斜槓)。
但是,你不想要一個正則表達式。您應該簡單地撥打replace()
,而不需要任何轉義。
使用'backslashes'逃跑。 –
不要在'contains()' – jlordo
中隱藏星號而且,您需要將'replaceAll()'的結果重新指定回字符串。字符串是不可變的,不會進行原地替換。 –