Java 替换所有的“&引用;带有“\\”字样&引用;在爪哇
是否可以将所有问号(“?”)替换为“\?” 假设我有一个字符串,我想删除该字符串的一些部分,其中一部分包含URL。像这样:Java 替换所有的“&引用;带有“\\”字样&引用;在爪哇,java,regex,string,Java,Regex,String,是否可以将所有问号(“?”)替换为“\?” 假设我有一个字符串,我想删除该字符串的一些部分,其中一部分包含URL。像这样: String longstring = "..."; //This is the long String String replacestring = "http://test.com/awesomeness.asp?page=27"; longstring.replaceAll(replacestring, ""); 但是!据我所知,不能将replaceAll()方法与
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring.replaceAll(replacestring, "");
但是!据我所知,不能将replaceAll()方法与包含一个问号的字符串一起使用,必须先将它们设置为“\?”
所以问题是,;有没有办法用字符串中的“\?”替换问号?不,我可以改变字符串
提前谢谢,希望有人能理解我!(很抱歉英语不好…请使用而不是:
使用,而使用纯文本。使用
\\\\?
也转义\
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring=longstring.replaceAll(replacestring, "\\\\?");
但正如其他答案所提到的,
replaceAll
有点过分,只需一个replace
就可以了。replaceAll
采用正则表达式,?
在正则表达式世界中具有特殊意义
在这种情况下,应该使用正则表达式,因为不需要正则表达式
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring = longstring.replace(replacestring, "");
哦,字符串是不可变的
longstring=longstring.replace(..)
,注意赋值 不要使用replaceAll()
,使用replace()
一种常见的误解是,replaceAll()
替换所有出现的内容,而replace()
只替换一个或多个内容。这是完全错误的
replaceAll()
名称不正确-它实际上替换了正则表达式。replace()
替换您想要的简单字符串
这两种方法都将替换目标的所有出现
只要这样做:
longstring = longstring.replace(replacestring, "");
这一切都会起作用。+1对于
常见的误解
部分。javadoc表示替换(CharSequence,CharSequence):用指定的文本替换序列替换与文本目标序列匹配的字符串的每个子字符串。@Elloco,你的观点是???我最终用“”拆分了字符串并重新生成字符串替换“?”(s)我想要…这实际上是可行的,但必须使用“\\\?”而不是“\\\?”。但正如波希米亚人和其他人所说;我将使用replace()代替。无论如何谢谢你!啊。修好了,谢谢。
longstring = longstring.replace(replacestring, "");