16

I have a String variable that contains '*' in it. But Before using it I have to replace all this character.

I've tried replaceAll function but without success:

text = text.replaceAll("*","");
text = text.replaceAll("*",null);

Could someone help me? Thanks!

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Viktor K
  • 2,153
  • 3
  • 25
  • 40

3 Answers3

52

Why not just use String#replace() method, that does not take a regex as parameter: -

text = text.replace("*","");

In contrary, String#replaceAll() takes a regex as first parameter, and since * is a meta-character in regex, so you need to escape it, or use it in a character class. So, your way of doing it would be: -

text = text.replaceAll("[*]","");  // OR
text = text.replaceAll("\\*","");

But, you really can use simple replace here.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
8

you can simply use String#replace()

text = text.replace("*","");

String.replaceAll(regex, str) takes regex as a first argument, as * is a metachacter you should escape it with a backslash to treat it as a normal charcter.

text.replaceAll("\\*", "")
PermGenError
  • 45,977
  • 8
  • 87
  • 106
3

Try this.

You need to escape the * for the regular expression, using .

text = text.replaceAll("\\*","");
Ajay S
  • 48,003
  • 27
  • 91
  • 111