replaceAll “/” with File.separator

ε祈祈猫儿з 提交于 2019-12-12 08:24:51

问题


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?


回答1:


It says it right there in the documentation:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll.

And, in Matcher.replaceAll:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

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);
    }
}

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));

This outputs:

a\b\c\d

as expected.




回答2:


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:

"a/b/c/d".replaceAll("/", Matcher.quoteReplacement(File.separator));



回答3:


Try This

    String str = "a/b/c/d";
    str = str.replace("/", File.separator);



回答4:


Try with str.replace('/', File.separatorChar)



来源:https://stackoverflow.com/questions/13714722/replaceall-with-file-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!