Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all "?" with "\\?" in Java [duplicate]

Tags:

java

string

regex

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

like image 357
GuiceU Avatar asked Dec 09 '12 20:12

GuiceU


2 Answers

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.

like image 198
Bohemian Avatar answered Sep 18 '22 15:09

Bohemian


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.

like image 40
PearsonArtPhoto Avatar answered Sep 17 '22 15:09

PearsonArtPhoto