5

我已经从这个答案中获取了匹配斜杠和反斜杠的正则表达式:Regex to match both slash in JAVA

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

但是,我收到错误:

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

这个正则表达式有什么问题?删除+不会改变任何东西,错误消息是一样的......

4

2 回答 2

11

它记录在Javadoc中:

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

所以你可以试试这个:

String replaced = path.replaceAll("[/\\\\]+", Matcher.quoteReplacement(System.
            getProperty("file.separator")));
于 2013-07-23T15:18:00.443 回答
1

这应该有效:

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

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

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

编辑结束

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

C:/system/properties/all/

因此它将“标准化”双分隔符。

于 2013-07-23T15:19:00.143 回答