iammilind
iammilind

Reputation: 70000

Problem with String::replaceFirst() when used with "*"?

private String unusedDigits = new String("0123456789*#");
unusedDigits = unusedDigits.replaceFirst("1", "");
//...
unusedDigits = unusedDigits.replaceFirst("*", ""); // <--- problem

Am a Java beginner. Why am I facing problem when using replaceFirst() with "*" ? It goes to some different code flow (which is related to some synchronized). If I comment that statement then things work fine !

Upvotes: 1

Views: 336

Answers (5)

Adithya Surampudi
Adithya Surampudi

Reputation: 4454

replaceFirst argument is a regex, and * has a specific meaning in regex, so to escape the regex part change to

unusedDigits = unusedDigits.replaceFirst("\\*", "");

Upvotes: 1

wjans
wjans

Reputation: 10115

replaceFirst takes a regular expression as it's first argument. Since * is a special character you need to escape it.

Try this:

unusedDigits = unusedDigits.replaceFirst("\\*", "");

Upvotes: 1

MByD
MByD

Reputation: 137382

In replaceFirst(), The first parameter is a regex. You can use Pattern.quote("*") instead:

unusedDigits = unusedDigits.replaceFirst(Pattern.quote("*"), "");

Upvotes: 2

Petar Ivanov
Petar Ivanov

Reputation: 93040

You should escape the * character, as it is a special regex character:

unusedDigits = unusedDigits.replaceFirst("\\*", "");

Upvotes: 2

bart
bart

Reputation: 2408

replaceFirst requires regular expression as an argument. '*' is a special character in regex so you should use

unusedDigits = unusedDigits.replaceFirst("\\*", ""); 

to replace it.

Upvotes: 1

Related Questions