12

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
  • 38,970
  • 17
  • 111
  • 142
GuiceU
  • 1,030
  • 6
  • 19
  • 35

4 Answers4

27

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
  • 412,405
  • 93
  • 575
  • 722
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
  • 38,970
  • 17
  • 111
  • 142
  • This actually works, but instead of "\\\?" you must have "\\\\?". But as Bohemian and the other guys said; I'll use replace() instead. Thanks anyway! – GuiceU Dec 09 '12 at 21:01
2

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

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

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

ccallendar
  • 888
  • 8
  • 10
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
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
  • 127,459
  • 24
  • 238
  • 287