United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
Bug ID: JDK-6325596 (spec) String.replaceFirst doc could be clearer about special characters in replacement string
JDK-6325596 : (spec) String.replaceFirst doc could be clearer about special characters in replacement string

Details
Type:
Bug
Submit Date:
2005-09-19
Status:
Closed
Updated Date:
2010-07-29
Project Name:
JDK
Resolved Date:
2005-10-14
Component:
core-libs
OS:
generic
Sub-Component:
java.lang
CPU:
generic
Priority:
P4
Resolution:
Duplicate
Affected Versions:
6
Fixed Versions:

Related Reports
Duplicate:
Relates:
Relates:
Relates:
Relates:

Sub Tasks

Description
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)".

                                    

Comments
EVALUATION

Trivial spec addition seems like it would be helpful.
                                     
2005-09-20
EVALUATION

I've just updated the api doc for replaceFirst/All with the notice
of "special treatment of backslash and dollar..." for bug#6280695
and #6193724. Close this one as the dup of those two.
                                     
2005-10-14



Hardware and Software, Engineered to Work Together