Replace dot in between slash i.e. ‘/./’ with single slash ‘/’

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")

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *