StringIndexOutOfBoundsException

"a/a/a/a/".replaceAll("/","\\")

Why does this generate:

StringIndexOutOfBoundsException: String index out of range: 1

at java.lang.String.charAt(Unknown Source)

at java.util.regex.Matcher.appendReplacement(Unknown Source)

at java.util.regex.Matcher.replaceAll(Unknown Source)

at java.lang.String.replaceAll(Unknown Source)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

at java.lang.reflect.Method.invoke(Unknown Source)

[641 byte] By [Nethera] at [2007-11-27 8:40:47]
# 1
a/a/a/a/.replaceAll("/","\\\\")
floundera at 2007-7-12 20:39:23 > top of Java-index,Java Essentials,Java Programming...
# 2
works...i dont get why
Nethera at 2007-7-12 20:39:23 > top of Java-index,Java Essentials,Java Programming...
# 3

\ is an escape character in both Java string literals and in regex

If you have "\\" in a Java string literal, it gets escaped by the compiler to \ which the regex sees. But for a single \ literal in the regex, the regex engine needs \\, which it will escape to \.

So "\\\\" gets turned into \\ by the compiler, which gets turned into \ by regex.

jverda at 2007-7-12 20:39:23 > top of Java-index,Java Essentials,Java Programming...
# 4
ah, thanks!
Nethera at 2007-7-12 20:39:23 > top of Java-index,Java Essentials,Java Programming...