gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:20:12 26 4
gpt4 key购买 nike

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

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

但是,我得到了错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

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

最佳答案

记录在 the Javadoc 中:

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. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

所以你可以试试这个:

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

关于Java - 用系统路径分隔符替换路径分隔符的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17814184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com