JDK-6325596 : (spec) String.replaceFirst doc could be clearer about special characters in replacement string
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 2005-09-19
  • Updated: 2010-07-29
  • Resolved: 2005-10-14
Related Reports
Duplicate :  
Relates :  
Relates :  
Relates :  
Relates :  
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 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.
14-10-2005

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