replaceAll" /"使用File.separator [英] replaceAll "/" with File.separator

查看:214
本文介绍了replaceAll" /"使用File.separator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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

并且,在中Matcher.replaceAll


请注意替换字符串中的反斜杠(\)和美元符号($)可能导致结果不同于将其视为文字替换字符串。如上所述,美元符号可被视为对捕获的子序列的引用,反斜杠用于替换替换字符串中的文字字符。

您需要做的是转义替换字符串中的任何转义字符,例如 Matcher.quoteReplacement()

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆