Java - 用系统路径分隔符替换所有路径分隔符实例

时间:2013-07-23 15:13:40

标签: java regex

我从这个答案中得到了斜杠和反斜杠的正则表达式:Regex to match both slash in JAVA

    String path = "C:\\system/properties\\\\all//";
    String replaced = path.replaceAll("[/\\\\]+", 
        System.getProperty("file.separator"));

然而,我收到错误:

  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:   字符串索引超出范围:1

这个正则表达式出了什么问题?删除+不会改变任何内容,错误消息是相同的......

2 个答案:

答案 0 :(得分:10)

记录在the Javadoc

  

请注意,替换字符串中的反斜杠(\)和美元符号($)可能会导致结果与将其视为文字替换字符串时的结果不同;见Matcher.replaceAll。如果需要,使用Matcher.quoteReplacement(java.lang.String)来抑制这些字符的特殊含义。

所以你可以试试这个:

String replaced = path.replaceAll("[/\\\\]+", Matcher.quoteReplacement(System.
            getProperty("file.separator")));

答案 1 :(得分:1)

这应该有效:

String path = "C:\\system/properties\\\\all//";

编辑:修改了以下内容的assylias'回答

System.out.println(path.replaceAll("(\\\\+|/+)", Matcher.quoteReplacement(System.getProperty("file.separator"))));

编辑结束

输出(对我来说 - 我使用的是mac):

C:/system/properties/all/

所以它会“正常化”双分隔符。

相关问题