是否可以用“\?”替换所有问号(“?”) ?
假设我有一个字符串,我想删除该字符串的某些部分,其中一部分包含URL。像这样:
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring.replaceAll(replacestring, "");
但是!据我所知,你不能将replaceAll()方法与包含一个单一问号的String一起使用,你必须使它们像这样“\?”第一
所以问题是;有没有办法用“\?”替换问号在一个字符串?不,我能够改变字符串。
提前致谢,希望有人理解我! (抱歉英语不好......)
答案 0 :(得分:19)
请勿使用replaceAll()
,请使用replace()
!
一种常见的误解是replaceAll()
取代所有次出现,而replace()
只是替换了一个或那样的东西。这完全是错误的。
replaceAll()
命名不佳 - 它实际上取代了正则表达式。
replace()
取代了简单的字符串,这就是你想要的。
这两种方法都会替换目标的所有次出现。
这样做:
longstring = longstring.replace(replacestring, "");
这一切都会奏效。
答案 1 :(得分:5)
使用\
也可以逃离\\\\?
。
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring=longstring.replaceAll(replacestring, "\\\\?");
但正如其他答案所提到的,replaceAll
有点矫枉过正,只有replace
应该有效。
答案 2 :(得分:2)
使用String.replace()
代替String.replaceAll()
:
longstring = longstring.replace("?", "\\?");
String.replaceAll()
使用Regular Expression,而String.replace()
使用纯文本。
答案 3 :(得分:2)
replaceAll
采用正则表达式,?
在正则表达式世界中具有特殊含义。
在这种情况下,您应该使用replace
,因为您不需要正则表达式。
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring = longstring.replace(replacestring, "");
哦,字符串是不变的!! longstring = longstring.replace(..)
,注意作业。