【发布时间】:2013-01-13 11:37:09
【问题描述】:
我有一个字符串变量,其中包含“*”。但在使用它之前,我必须替换所有这些字符。
我尝试了 replaceAll 功能但没有成功:
text = text.replaceAll("*","");
text = text.replaceAll("*",null);
有人可以帮我吗?谢谢!
【问题讨论】:
标签: java android string replace
我有一个字符串变量,其中包含“*”。但在使用它之前,我必须替换所有这些字符。
我尝试了 replaceAll 功能但没有成功:
text = text.replaceAll("*","");
text = text.replaceAll("*",null);
有人可以帮我吗?谢谢!
【问题讨论】:
标签: java android string replace
为什么不直接使用String#replace() 方法,它不使用regex 作为参数:-
text = text.replace("*","");
相反,String#replaceAll() 将正则表达式作为第一个参数,并且由于 * 是正则表达式中的 元字符,因此您需要对其进行转义,或者在字符类中使用它.所以,你的做法是:-
text = text.replaceAll("[*]",""); // OR
text = text.replaceAll("\\*","");
但是,你真的可以在这里使用简单的替换。
【讨论】:
你可以简单地使用String#replace()
text = text.replace("*","");
String.replaceAll(regex, str) 将正则表达式作为第一个参数,因为* 是一个元字符,您应该使用反斜杠对其进行转义以将其视为普通字符。
text.replaceAll("\\*", "")
【讨论】:
试试这个。
您需要为正则表达式转义 *,使用 .
text = text.replaceAll("\\*","");
【讨论】: