Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing slashes from a string path in java

Tags:

java

String path = "/var/lib/////xen//images///rhel";

the number of slashes can be of any number. How to normalize the path in java like :

/var/lib/xen/images/rhel
like image 868
Amby Avatar asked May 06 '13 16:05

Amby


3 Answers

Use the built-in String method replaceAll, with a regular expression "/+", replacing one or more slashes with one slash:

path = path.replaceAll("/+", "/");
like image 73
rgettman Avatar answered Oct 13 '22 01:10

rgettman


You could use a File object to output the path specific to the current platform:

String path = "/var/lib/////xen//images///rhel";
path = new File(path).getPath();
like image 25
Reimeus Avatar answered Oct 13 '22 01:10

Reimeus


Use Guava's CharMatcher:

String simplifiedPath = CharMatcher.is('/').collapseFrom(originalPath, '/');

See: Guava Explained > Strings > CharMatcher

like image 42
Sean Patrick Floyd Avatar answered Oct 13 '22 01:10

Sean Patrick Floyd