JDK-6325587 : String.replaceFirst(token, value) gives java.lang.IndexOutOfBoundsException
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_2000
  • CPU: x86
  • Submitted: 2005-09-19
  • Updated: 2010-04-02
  • Resolved: 2005-09-19
Related Reports
Relates :  
Description
FULL PRODUCT VERSION :
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_04-b05)
Java HotSpot(TM) Client VM (build 1.5.0_04-b05, mixed mode, sharing)

ADDITIONAL OS VERSION INFORMATION :
Window 2000, Service Pack 4

A DESCRIPTION OF THE PROBLEM :
Exception occurs when I try to replace a token with a value, and the value has $ in it.








STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
public class Test
{
    public static void main(String[] args)
    {
         String temp = "I have <MONEY_AMOUNT>  to pay you";
         temp = temp.replaceFirst("<MONEY_AMOUNT>", "$2.5");
         System.out.println(temp);
    }
}


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
I have $2.5  to pay you
ACTUAL -
Exception in thread error

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 2
	at java.util.regex.Matcher.group(Unknown Source)
	at java.util.regex.Matcher.appendReplacement(Unknown Source)
	at java.util.regex.Matcher.replaceFirst(Unknown Source)
	at java.lang.String.replaceFirst(Unknown Source)
	at Smart2K.Version.main(Version.java:147)

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
public class Test
{
    public static void main(String[] args)
    {
         String temp = "I have <MONEY_AMOUNT>  to pay you";
         temp = temp.replaceFirst("<MONEY_AMOUNT>", "$2.5");
         System.out.println(temp);
    }
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Put the dollar sign before the token, and just replace the token with number.

Comments
EVALUATION Use java.util.regex.Matcher.quoteReplacement: temp = temp.replaceFirst("<MONEY_AMOUNT>", java.util.regex.Matcher.quoteReplacement("$2.5"));
19-09-2005