Android系统.从String中替换*字符

Vik*_*r K 15 java string android replace

我有一个String变量,其中包含'*'.但在使用之前我必须更换所有这个角色.

我尝试过replaceAll函数,但没有成功:

text = text.replaceAll("*","");
text = text.replaceAll("*",null);
Run Code Online (Sandbox Code Playgroud)

有人能帮助我吗?谢谢!

Roh*_*ain 47

为什么不使用String#replace()方法,不采用regex参数: -

text = text.replace("*","");
Run Code Online (Sandbox Code Playgroud)

相反,String#replaceAll()将正则表达式作为第一个参数,并且因为*是正则表达式中的元字符,所以您需要将其转义,或者在字符类中使用它.所以,你这样做的方式是: -

text = text.replaceAll("[*]","");  // OR
text = text.replaceAll("\\*","");
Run Code Online (Sandbox Code Playgroud)

但是,你真的可以在这里使用简单的替换.


Per*_*ror 7

你可以简单地使用 String#replace()

text = text.replace("*","");
Run Code Online (Sandbox Code Playgroud)

String.replaceAll(regex,str)将正则表达式作为第一个参数,因为*你应该使用反斜杠将其转义为metachacter,将其视为普通字符.

text.replaceAll("\\*", "")
Run Code Online (Sandbox Code Playgroud)