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("\\*", "");
加载中,请稍侯......
精彩评论