简体   繁体   English

用File.separator替换所有“/”

[英]replaceAll “/” with File.separator

In Java, when I do: 在Java中,当我这样做时:

    "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. 它抛出一个StringIndexOutOfBoundsException,我不知道为什么。 I tried looking this up, but it wasn't very helpful. 我试着看一下,但这不是很有帮助。 Can anyone help me out? 谁能帮我吗?

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 . Matcher.replaceAll

And, in Matcher.replaceAll : 并且,在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() : 您需要做的是转义替换字符串中的任何转义字符,例如使用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: 注意,我在sep使用文字\\\\而不是直接使用File.separator ,因为我的分隔符是UNIX - 您应该能够使用:

s = s.replaceAll("/", Matcher.quoteReplacement(File.separator));

This outputs: 这输出:

a\b\c\d

as expected. 正如所料。

File.separator is \\ on Windows, that is; File.separator在Windows上是\\ ,即; 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. 所以你必须逃避它两次,一次用于Java,一次用于替换字符串。

This should work: 这应该工作:

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

Try This 试试这个

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

尝试使用str.replace('/', File.separatorChar)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM