用斜杠替换斜线之间的点即'/./''/'

Sau*_*ahu 4 java regex replace

对于这个字符串dirPath,

String dirPath = "c:/create/a/dir/very/deep/inside/../././../../../dir/";
Run Code Online (Sandbox Code Playgroud)

我希望输出字符串看起来像:

"c:/create/a/dir/very/deep/inside/../../../../dir/";
Run Code Online (Sandbox Code Playgroud)

我用了 :

dirPath.replaceAll("/[.]/", "/");
Run Code Online (Sandbox Code Playgroud)

但那给了:

c:/create/a/dir/very/deep/inside/.././../../../dir/
                                   ^^^ 
Run Code Online (Sandbox Code Playgroud)

然后,再试一次replaceAll:

dirPath.replaceAll("/[.]/", "/").replaceAll("/[.]/", "/");
Run Code Online (Sandbox Code Playgroud)

那工作!

我的问题是为什么一个电话无法达到相同的结果?如何以最简单的方式实现它?

PS另一个对我不起作用的正则表达式: .replaceAll("($|/)[.]/", "$1")

blh*_*ing 5

您可以使用超前模式来避免消耗后续匹配所需的斜杠:

dirPath.replaceAll("/\\.(?=/)", "")
Run Code Online (Sandbox Code Playgroud)

演示:https://regex101.com/r/qWKVU3/1http://tpcg.io/ijmYJF