Search code examples
javaspecial-charactersreplaceall

Using replaceAll with Strings containing special characters in Java


Basically, this is what I'm trying to do is this:

String s = "to+go+la";

s.replaceAll("to+go", "");

which should return "+la"

I know that if I were to just replace the + signs, I would use \\+, but I'm not sure what I what to do when the signs are embeded. Is the best answer to just remove them from both? This will work for my purposes, but it seems like a duct tape answer.


Solution

  • Your case doesn't call for a regex, so it is inappropriate to use it. It's both slower and more cumbersome. Use a plain and simple replace instead of replaceAll and you won't need to escape anything:

    String s = "to+go+la".replace("to+go", "");