2013-03-22 19 views
0

我有兩個字符串,並希望從另一個字符串中替換一個字符串。問題是字符串具有元字符。在具有元字符的java中替換字符串

E.g.

String string1 = "I am foo"; 
String string2 = "I am bar and I am foo. I am both."; 
string2 = string2.replaceAll(string1, ""); does the replacement. 

假設我有以下字符串。

String string1 = "I + am - foo []."; 
String string2 = "I + am bar and I + am - foo []. I am both."; 

Then the answer should be : "I + am bar and I am both." 

我們該如何進行更換? 我知道 java.util.regex.Pattern.quote("xyz")轉義字符,但在這種情況下,有許多元字符。

謝謝。

+1

我不明白爲什麼'模式#報價()'這裏行不通。你能詳細說明一下嗎? – 2013-03-22 20:02:39

回答

0

您似乎已經有了答案:

String string1 = "I + am - foo []."; 
String string2 = "I + am bar and I + am - foo []. I am both."; 
System.out.println(string2.replaceAll(Pattern.quote(string1), "")); 

輸出:

I + am bar and I am both.