Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - regular expression to split directory paths

Tags:

java

regex

split

I am trying to do the following in Java
give a directory path like "/a/b/c" I want to get a array of string as ["a", "b", "c"]. The code is as follows :

private static final String DIRECTORY_PATH_SEPARATOR = "/";  
    Iterator iter = testPaths.iterator();

            String[] directories;

        while( iter.hasNext() ) {

            directories = ( ( String ) iter.next() ).split(DIRECTORY_PATH_SEPARATOR);
        }

but what i get as array is space as well. I want to get all those strings with length>0.
how can I do that??

like image 212
daydreamer Avatar asked Nov 01 '10 06:11

daydreamer


Video Answer


2 Answers

The only place you'd get an empty string (in a valid path) would be the first item if the path started with the separator. If it had the leading separator, split on the path without it.

String path = "/a/b/c";
String[] directories = path.substring(1).split(DIRECTORY_PATH_SEPARATOR);
// { "a", "b", "c" }

As noted by OmnipotentEntity, my assumption was wrong about valid paths. You'd otherwise have to go through the array and keep nonempty strings when using split().

String path = "/a/b////c";
String[] split = path.split(DIRECTORY_PATH_SEPARATOR);
ArrayList<String> directories = new ArrayList<String>(split.length);
for (String dir : split)
    if (dir.length() > 0)
        directories.add(dir);

An alternative is to use actual regular expressions to match non-separator characters:

String path = "/a/b////c";
ArrayList<String> directories = new ArrayList<String>();
Pattern regex = Pattern.compile("[^" + DIRECTORY_PATH_SEPARATOR + "]+");
Matcher matcher = regex.matcher(path);
while (matcher.find())
    directories.add(matcher.group());
like image 81
Jeff Mercado Avatar answered Sep 24 '22 09:09

Jeff Mercado


You should use the File class for this, not a regex.

like image 32
user207421 Avatar answered Sep 23 '22 09:09

user207421