|
Duplicate :
|
|
|
Relates :
|
|
|
Relates :
|
|
|
Relates :
|
|
|
Relates :
|
Bug 6325587 reports a problem in using String.replaceFirst like this:
"I have <MONEY_AMOUNT> to pay you".replaceFirst("<MONEY_AMOUNT>", "$2.5")
which produces:
java.lang.IndexOutOfBoundsException: No group 2
That bug has been closed as "not a defect" since this is the intended behaviour.
However, I think this is a documentation problem. You have to track through the documentation quite carefully to discover that the characters \ and $ have a special meaning in the replacement string. It could be helpful to copy this sentence from Matcher.replaceAll into all of String.replaceFirst, String.replaceAll, and Matcher.replaceFirst:
"Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string."
We could also add a sentence like this in all four places:
"If the replacement string is supposed to be a literal replacement string and it might contain these characters, {@link Matcher#quoteReplacement} can be used."
Finally, the exception message shown could perhaps be improved, if only to say "No group $2" rather than just "No group 2", or more wordily "Replacement string contains $2 but regular expression has 0 group(s)".
|