-
Bug
-
Resolution: Duplicate
-
P4
-
None
-
1.4.1
-
x86
-
linux
Name: rmT116609 Date: 04/03/2003
FULL PRODUCT VERSION :
java version "1.4.1_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)
FULL OPERATING SYSTEM VERSION : glibc-2.2.5-34, Linux
server 2.4.18-3 #1 Thu Apr 18 07:31:07 EDT 2002 i686
unknown, Red Hat Linux release 7.3 (Valhalla)
A DESCRIPTION OF THE PROBLEM :
The use of backslashes in the replacement string of the
java.util.Matcher class is not documented properly. The
javadoc entry of appendReplacement() mentions that a
backslash can be used to escape a $, but it doesn't
mention that if the user wants an actual backslash, they
need to use two. (In a string they need to type four.)
The following causes StringIndexOutOfBoundsException:
String filename = "/abc/def";
filename = filename.replaceAll("/", "\\");
because the appendReplacement() code tries to append the
character after the backslash and the charAt() dies. The
correct code is:
filename = filename.replaceAll("/", "\\\\");
which is certainly not obvious from the documentation. Up
to you whether this is a bug in the implementation or in
the documentation.
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
1. Type in code above.
2. Run it.
3. See exception.
EXPECTED VERSUS ACTUAL BEHAVIOR :
I either expect the code to work (handle a single
backslash in the string as a single backslash) or I expect
the exception to be more meaningful
(InvalidReplacementException). The out-of-bounds
exception is a side-effect of the implementation and makes
no sense to the user. In fact, until I read the Matcher
source code, I had no idea whether the exception referred
to the regexp or in the replacement.
ERROR MESSAGES/STACK TRACES THAT OCCUR :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 1
at java.lang.String.charAt(String.java:460)
at java.util.regex.Matcher.appendReplacement(Matcher.java:544)
at java.util.regex.Matcher.replaceAll(Matcher.java:646)
at java.lang.String.replaceAll(String.java:1710)
at Test.main(Test.java:7)
REPRODUCIBILITY :
This bug can be reproduced always.
---------- BEGIN SOURCE ----------
class Test {
public static void main(String[] args) {
String filename = "m:/abc/def/hello.mp3";
System.out.println("Before: " + filename);
filename = filename.replaceAll("/", "\\");
System.out.println("After: " + filename);
}
}
---------- END SOURCE ----------
CUSTOMER WORKAROUND :
Type four backslashes instead of two in the replacement string.
(Review ID: 180904)
======================================================================
- duplicates
-
JDK-4684543 appendReplacement/replaceAll replacement string not documented completely
-
- Closed
-