In Java, when I do:
"a/b/c/d".replaceAll("/", "@");
I get back
a@b@c@d
But when I do:
"a/b/c/d".replaceAll("/", File.separator);
It throws a StringIndexOutOfBoundsException, and I don't know why. I tried looking this up, but it wasn't very helpful. Can anyone help me out?
Try with
str.replace('/', File.separatorChar)
Try This
It says it right there in the documentation:
And, in
Matcher.replaceAll
:What you need to do is to escape any escape characters you have in the replacement string, such as with
Matcher.quoteReplacement()
:Note, I'm using the literal
\\
insep
rather than usingFile.separator
directly since my separator is the UNIX one - you should be able to just use:This outputs:
as expected.
File.separator
is\
on Windows, that is; it is an escaped backslash. However, in a replacement string, it means something completely different. So you'd have to escape it twice, once for Java, and once for replacement string.This should work: