简体   繁体   English

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

[英]Replace dot in between slash i.e. '/./' with single slash '/'

For this string dirPath , 对于这个字符串dirPath

String dirPath = "c:/create/a/dir/very/deep/inside/../././../../../dir/";

I want the output string to look like : 我希望输出字符串看起来像:

"c:/create/a/dir/very/deep/inside/../../../../dir/";

I used : 我用了 :

dirPath.replaceAll("/[.]/", "/");

but that gave : 但那给了:

c:/create/a/dir/very/deep/inside/.././../../../dir/
                                   ^^^ 

then, tried with one more replaceAll as: 然后, replaceAll一次替换所有:

dirPath.replaceAll("/[.]/", "/").replaceAll("/[.]/", "/");

and that worked! 那工作!

My question is why couldn't one call achieve the same result? 我的问题是为什么一个电话无法达到相同的结果? How to achieve it in simplest way? 如何以最简单的方式实现它?

PS Another regex that didn't work for me : .replaceAll("($|/)[.]/", "$1") PS另一个对我不起作用的正则表达式: .replaceAll("($|/)[.]/", "$1")

You can use a lookahead pattern to avoid consuming the slash needed by the subsequent match: 您可以使用超前模式来避免消耗后续匹配所需的斜杠:

dirPath.replaceAll("/\\.(?=/)", "")

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM