java字符串操作,将多个斜杠更改为一个斜杠

java字符串操作,将多个斜杠更改为一个斜杠,java,string,replaceall,Java,String,Replaceall,愚蠢的错误用+代替+ 总之,我正在尝试将输入路径中的所有/+转换为/以简化unix风格的路径 path.replaceAll( "/+", "/"); path.replaceAll( "\\/+", "/"); 结果是什么都没做,正确的做法是什么 public class SimplifyPath { public String simplifyPath(String path) { Stack<String> direc = new Stack<Strin

愚蠢的错误用+代替+

总之,我正在尝试将输入路径中的所有/+转换为/以简化unix风格的路径

 path.replaceAll( "/+", "/"); 
 path.replaceAll( "\\/+", "/"); 
结果是什么都没做,正确的做法是什么

public class SimplifyPath {
public String simplifyPath(String path) {
    Stack<String> direc = new Stack<String> ();
    path = path.replaceAll("/+", "/");
    System.out.println("now path becomes " + path);  // here path remains "///"

    int i = 0;
    while (i < path.length() - 1) {
        int slash = path.indexOf("/", i + 1);
        if (slash == -1) break;
        String tmp = path.substring(i, slash);
        if (tmp.equals("/.")){
            continue;
        } else if (tmp.equals("/..")) {
            if (! direc.empty()){
                direc.pop();
            }
            return "/";
        } else {
            direc.push(tmp);
        }
        i = slash;
    }
    if (direc.empty()) return "/";
    String ans = "";
    while (!direc.empty()) {
        ans = direc.pop() + ans;
    }
    return ans;
}

public static void main(String[] args){
    String input = "///";
    SimplifyPath test = new SimplifyPath();
    test.simplifyPath(input);
 }
}
您使用的是+,而不是+。这是一个不同的角色

替换

path = path.replaceAll("/+", "/");

您使用的是+,而不是+。这是一个不同的角色

替换

path = path.replaceAll("/+", "/");


您是否尝试过使用File.separator。。。这比\或/更安全,因为Linux和Windows使用不同的文件分隔符。使用File.separator将使您的程序运行,而不管它在哪个平台上运行,毕竟,这是JVM的要点。-正斜杠可以工作,但是File.separator会让您的最终用户更加相信它会工作。 例如路径:Test/World

String fileP = "Test" + File.separator + "World";

您是否尝试过使用File.separator。。。这比\或/更安全,因为Linux和Windows使用不同的文件分隔符。使用File.separator将使您的程序运行,而不管它在哪个平台上运行,毕竟,这是JVM的要点。-正斜杠可以工作,但是File.separator会让您的最终用户更加相信它会工作。 例如路径:Test/World

String fileP = "Test" + File.separator + "World";

那么你想把//a//b//c转换成/a/b/c

public static void main(String[] args) {
    String x = "///a//b//c";
    System.out.println(x.replaceAll("/+", "/"));
}
你应该去玩这个把戏

如果实际上需要/++->/转换,则需要转义+,而不是/

public static void main(String[] args) {
    String x = "/+/+/a//b/+/c";
    System.out.println(x.replaceAll("/\\+", "/"));
}

那么你想把//a//b//c转换成/a/b/c

public static void main(String[] args) {
    String x = "///a//b//c";
    System.out.println(x.replaceAll("/+", "/"));
}
你应该去玩这个把戏

如果实际上需要/++->/转换,则需要转义+,而不是/

public static void main(String[] args) {
    String x = "/+/+/a//b/+/c";
    System.out.println(x.replaceAll("/\\+", "/"));
}

尝试path.replaceAll\\/+,/;这也不起作用,这是java版本问题吗?请尝试path.replaceAll\\/+,/;这也不起作用,这是java版本问题吗?此用户有以下答案:此用户有以下答案: