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 :


I used :

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

but that gave :


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


You can use a lookahead pattern to avoid consuming the slash needed by the subsequent match:

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

Demo: or

Leave a Reply

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