问题描述
在Java中,当我这样做时:
In Java, when I do:
"a/b/c/d".replaceAll("/", "@");
我回来了
a@b@c@d
但是当我这样做时:
"a/b/c/d".replaceAll("/", File.separator);
它抛出一个StringIndexOutOfBoundsException,我不知道为什么。我试着看一下,但这不是很有帮助。任何人都可以帮助我吗?
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?
推荐答案
它在:
并且,在中Matcher.replaceAll
:
您需要做的是转义替换字符串中的任何转义字符,例如:
What you need to do is to escape any escape characters you have in the replacement string, such as with Matcher.quoteReplacement()
:
import java.io.File;
import java.util.regex.Matcher;
class Test {
public static void main(String[] args) {
String s = "a/b/c/d";
String sep = "\\"; // File.separator;
s = s.replaceAll("/", Matcher.quoteReplacement(sep));
System.out.println(s);
}
}
注意,我正在使用文字 \\
在 sep
中,而不是直接使用 File.separator
我的分隔符是UNIX分隔符 - 你应该可以使用:
Note, I'm using the literal \\
in sep
rather than using File.separator
directly since my separator is the UNIX one - you should be able to just use:
s = s.replaceAll("/", Matcher.quoteReplacement(File.separator));
此输出:
a\b\c\d
符合预期。
这篇关于replaceAll" /"使用File.separator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!