Reputation: 13934
For this string 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:
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?
P.S. Another regex that didn't work for me : .replaceAll("($|/)[.]/", "$1")
Upvotes: 4
Views: 191
Reputation: 106533
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
Upvotes: 5