remove unneccesarry path transveral in unix path by regex which create with . and

huangapple go评论89阅读模式
英文:

remove unneccesarry path transveral in unix path by regex which create with . and

问题

这个路径(str = /tmp/a/b/12-3/ab-c/1-23/../../real/env.sh)有不必要的/ab-c/1-23/../..,我想通过Java中的正则表达式将其移除。我尝试了多个正则表达式模式,但都没有起作用。

英文:

this path (str = /tmp/a/b/12-3/ab-c/1-23/../../real/env.sh) have unnesarry /ab-c/1-23/../.. i like to remove this in by regex in java . I tried multiple regex pattern but it not working .

答案1

得分: 1

这并不是一个好主意,认为正则表达式是解决所有字符串问题的方法。在你的情况下,最好使用 File 类的 getCanonicalPath() 方法:

String path = "/tmp/a/b/12-3/ab-c/1-23/../../real/env.sh";
String canonical = new File(path).getCanonicalPath();
// "/tmp/a/b/12-3/real/env.sh"
System.out.println(canonical);

但是为了向你展示,这里有一种可能的使用正则表达式的方法:

String path = "/tmp/a/b/12-3/ab-c/1-23/../../real/env.sh";
while (path.matches("^.*\\/{2}.*$")) {
    path = path.replaceFirst("\\/[\\w-]+\\/{2}", "");
}
// "/tmp/a/b/12-3/real/env.sh"
System.out.println(path);
英文:

It is not a good idea to consider that regex is a solution for all string problems. In your case, it is better to use getCanonicalPath() of the File class:

String path = "/tmp/a/b/12-3/ab-c/1-23/../../real/env.sh";
String canonical = new File(path).getCanonicalPath();
// "/tmp/a/b/12-3/real/env.sh"
System.out.println(canonical);

But just to show you, here a possible way by using regex:

String path = "/tmp/a/b/12-3/ab-c/1-23/../../real/env.sh";
while (path.matches("^.*\\/\\.{2}.*$")) {
    path = path.replaceFirst("\\/[\\w-]+\\/\\.{2}", "");
}
// "/tmp/a/b/12-3/real/env.sh"
System.out.println(path);

</details>



huangapple
  • 本文由 发表于 2020年8月27日 13:54:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63609963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定