11

is it possible to replace all the questionmarks ("?") with "\?" ?

Lets say I have a String, and I want to delete some parts of that String, one part with an URL in it. Like this:

String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring.replaceAll(replacestring, "");

But! As I understand it you can't use the replaceAll() method with a String that contains one single questionmark, you have to make them like this "\?" first.

So the question is; Is there some way to replace questionmarks with "\?" in a String? And no, I'm able to just change the String.

Thanks in advance, hope someone understands me! (Sorry for bad English...)

PearsonArtPhoto
  • 37,474
  • 17
  • 109
  • 139
GuiceU
  • 950
  • 6
  • 18
  • 35

4 Answers4

25

Don't use replaceAll(), use replace()!

It is a common misconception that replaceAll() replaces all occurrences and replace() just replaces one or something. This is totally incorrect.

replaceAll() is poorly named - it actually replaces a regex.
replace() replaces simple Strings, which is what you want.

Both methods replace all occurrences of the target.

Just do this:

longstring = longstring.replace(replacestring, "");

And it will all work.

Bohemian
  • 389,931
  • 88
  • 552
  • 692
4

Escape the \ too, using \\\\?.

String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring=longstring.replaceAll(replacestring, "\\\\?");

But as other answer have mentioned, replaceAll is a bit overkill, just a replace should work.

PearsonArtPhoto
  • 37,474
  • 17
  • 109
  • 139
2

Use String.replace() instead of String.replaceAll():

longstring = longstring.replace("?", "\\?");

String.replaceAll() uses Regular Expression, while String.replace() uses plain text.

ccallendar
  • 848
  • 7
  • 10
Eng.Fouad
  • 111,301
  • 67
  • 311
  • 403
2

replaceAll takes a regular expression, and ? has a special meaning in the regex world.

You should use replace in this case, since you don't need a regex.

String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring = longstring.replace(replacestring, "");

Oh, and strings are immutable!! longstring = longstring.replace(..), notice the assignment.

arshajii
  • 123,543
  • 24
  • 232
  • 276