Replace all "?" from "\\?" in java

you can replace all question marks ("?") with "\?"

Let's say I have a String, and I want to delete some parts of this string, one part with the 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 far as I understand, you cannot use the replaceAll () method with String, which contains one question mark, you should make them like "\?" . first.

So the question is: Is there a way to replace the question marks with "\?" in line? And no, I can just change the line.

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

+7
source share
4 answers

Do not use replaceAll() , use replace() !

It is a common misconception that replaceAll() replaces all occurrences, and replace() simply replaces one or something. This is absolutely untrue.

replaceAll() poorly named - it actually replaces the regular expression.
replace() replaces the simple strings you need.

Both methods replace all occurrences of the target.

Just do the following:

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

And everything will work.

+16
source

Escape from \ using \\\\? .

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

But, as another answer said, replaceAll bit overkill, only replace should work.

+5
source

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

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

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

+2
source

replaceAll accepts a regex, ? is of particular importance in the world of regex.

In this case, you should use replace , since you do not need a regular expression.

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

Oh and the lines are immutable !! longstring = longstring.replace(..) , pay attention to the purpose.

+2
source

All Articles