【问题标题】:Java how to replace backslash? [duplicate]Java如何替换反斜杠? [复制]
【发布时间】:2011-08-11 00:50:23
【问题描述】:

在 java 中,我有一个文件路径,例如 'C:\A\B\C',我希望它更改为 ''C:/A/B/C'。如何替换反斜杠?

【问题讨论】:

标签: java regex


【解决方案1】:
    String text = "C:\\A\\B\\C";
    String newString = text.replace("\\", "/");
    System.out.println(newString);

【讨论】:

    【解决方案2】:

    由于您要求使用正则表达式,因此您必须多次转义“\”字符:

    String path = "c:\\A\\B\\C";
    System.out.println(path.replaceAll("\\\\", "/"));
    

    【讨论】:

    • +1 用于注意(并响应)“正则表达式”标签,即使问题实际上不需要正则表达式。
    【解决方案3】:

    您可以使用 String.replace 方法来做到这一点:

    public static void main(String[] args) {
        String foo = "C:\\foo\\bar";
        String newfoo = foo.replace("\\", "/");
        System.out.println(newfoo);
    }
    

    【讨论】:

      【解决方案4】:
      String oldPath = "C:\\A\\B\\C";
      String newPath = oldPath.replace('\\', '/');
      

      【讨论】:

        【解决方案5】:

        替换所有出现的给定字符:

        String result = candidate.replace( '\\', '/' );
        

        问候, 西里尔

        【讨论】:

        • 这不会编译。你需要'\\' 而不是'\'
        • 本质上,'\\' 是一个转义的 '\' 字符
        • @Cyril - 我查过了,你的答案是正确的!对不起。我删除了我的愚蠢评论。
        猜你喜欢
        • 2014-09-09
        • 2011-09-06
        • 1970-01-01
        • 2018-06-07
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        相关资源
        最近更新 更多