开发者

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

private String unusedDigits = n开发者_StackOverflow中文版ew 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 !


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

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


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

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


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

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

to replace it.


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("\\*", "");


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜