如何使用 Java 减少路径表达式中的双点

How to reduce double dots in path expressions using Java

我正在制作一个 Java 应用程序,它特别采用

形式的相对文件路径
String path = "path/to/Plansystem/Xslt/omraade/../../../Kms/Xslt/Rense/Template.xslt"

并减少/简化路径表达式,以便它提供等效路径,但没有双点。也就是说,我们应该得到这个字符串:

String result = "path/to/Kms/Xslt/Rense/Template.xslt"

目前,我定义了以下正则表达式:

String parentDirectory = $/\/(?!\.)([\w,_-]*)\.?([\w,_-]*)\/\.\.\//$

然后我将所有匹配项替换为单斜杠。这种方法似乎可行,我想出了使用 Regexr.com 的表达式,但在我看来我的方法有点老套,如果这个特定功能在某些经过良好测试的情况下不可用,我会感到惊讶,发达的图书馆。有人熟悉这样的图书馆吗?

编辑: 根据 rzwitserloot 和 Andy Turner 的回复,我意识到以下方法对我有用:

public static String slash = "/"
public static final String backslashes = $/\+/$

static String normalizePath(String first, String... more) {
      String pathToReturn = Paths.get(first, more).normalize().toString().replaceAll(backslashes, slash)
      return pathToReturn
}

请注意,我最后所做的替换只是出于我的特定需要,我想保留 unix 符号(即使 Windows 上的 运行)。

使用java.nio.Path:

Path path = Paths.get("path/to/Plansystem/Xslt/omraade/../../../Kms/Xslt/Rense/Template.xslt");
Path normalized = path.normalize();

不,不要为正则表达式烦恼。为此有一个 API!

基本 'dot' 移除:

import java.nio.file.Paths;

Paths.get("/Users/Birdie/../../Users/Birdie/workspace/../workspace").normalize()

将为您提供代表 /Users/Birdie/workspace.

的路径

您可以更进一步并关注软链接,甚至:

Paths.get("/Users/Birdie/../../Users/Birdie/workspace/../workspace").toRealPath()