0

I have two strings and want to replace one string from the other. The problem is that strings have meta characters.

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.

Suppose I have the following strings.

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."

How can we perform the replacement? I know java.util.regex.Pattern.quote("xyz") escapes the characters, but in this case, there are many meta characters.

Thanks.

mehdi lotfi
  • 11,194
  • 18
  • 82
  • 128
user2200660
  • 1,261
  • 3
  • 18
  • 23

1 Answers1

0

Seems like you already have the answer:

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), ""));

Output:

I + am bar and  I am both.
ach
  • 6,164
  • 1
  • 25
  • 28