我基本上尝试使用正则表达式将 "dir1/dir2/../dir3"
转换为 "dir1/dir3"
,如下所示:
filePath.replaceAll("^(\\w)?(<>:\"/\\|?*)//\\.\\./", "");
我在这里做错了什么?
我知道有很多规范化规则,但我只想应用两个规则:
All "." segments are removed.
If a ".." segment is preceded by a non-".." segment then both of these segments are removed. This step is repeated until it is no longer applicable.
我也尝试过:
result = filePath.replace("^(\\w+)\\.\\./", "");
但也没成功
最佳答案
您不能为此使用正则表达式(是的,像您的示例这样的简单情况可能会起作用,但对于更复杂的模式会很快崩溃)。既然你用的是java,那就看看java.net.URI.normalize()
:
Normalizes this URI's path ... If a ".." segment is preceded by a non-".." segment then both of these segments are removed. This step is repeated until it is no longer applicable. ...
关于java - 降低相对/规范路径的复杂性? (如何消除 ".."?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8069796/