JDK-8065421 : String replaceAll can throw StringIndexOutOfBoundsException
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 7u51
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_7
  • CPU: x86_64
  • Submitted: 2014-11-14
  • Updated: 2014-11-20
  • Resolved: 2014-11-20
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows [Version 6.1.7601]

A DESCRIPTION OF THE PROBLEM :
"_".replaceAll("_", "\\") causes a StringIndexOutOfBoundsException.

This exception is not documented to be thrown from this method.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

I think the reason behind this is that the regex engine is seeing the escape character \, with nothing afterward to escape. In my opinion, this should instead be thrown as a PatternSyntaxException, as documented.

Additionally, "ABC".replaceAll("_", "\\") does not throw an exception, probably because the regex causing the exception is never evaluated. Perhaps this should fail fast, so that an invalid regex will not be a surprise during runtime.


REPRODUCIBILITY :
This bug can be reproduced always.


Comments
This is a duplicate of JDK-7067045 which is fixed in JDK 8. Users can upgrade. Exception is changed from StringIndexOutofBounds to an IAE. No plans to backport to JDK 7u.
20-11-2014

This bug seems to be fixed in JDK 8 and 9: Exception in thread "main" java.lang.IllegalArgumentException: character to be escaped is missing at java.util.regex.Matcher.appendExpandedReplacement(Matcher.java:910) at java.util.regex.Matcher.appendReplacement(Matcher.java:889) at java.util.regex.Matcher.replaceAll(Matcher.java:1071) at java.lang.String.replaceAll(String.java:2211) at stuff.PatternTest.main(PatternTest.java:45) However with JDK 7u45 it produces the StringIndexOutOfBoundsException exception: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.charAt(String.java:658) at java.util.regex.Matcher.appendReplacement(Matcher.java:762) at java.util.regex.Matcher.replaceAll(Matcher.java:906) at java.lang.String.replaceAll(String.java:2162) at stuff.PatternTest.main(PatternTest.java:45)
20-11-2014