英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论