[java] How to parse this string in Java?

prefix/dir1/dir2/dir3/dir4/..

How to parse the dir1, dir2 values out of the above string in Java?

The prefix here can be:

/usr/local/apache2/resumes

This question is related to java string

The answer is


String str = "/usr/local/apache/resumes/dir1/dir2";
String prefix = "/usr/local/apache/resumes/";

if( str.startsWith(prefix) ) {
  str = str.substring(0, prefix.length);
  String parts[] = str.split("/");
  // dir1=parts[0];
  // dir2=parts[1];
} else {
  // It doesn't start with your prefix
}

...
String str = "bla!/bla/bla/"

String parts[] = str.split("/");

//To get fist "bla!"
String dir1 = parts[0];

public class Test {
    public static void main(String args[]) {
    String s = "pre/fix/dir1/dir2/dir3/dir4/..";
    String prefix = "pre/fix";
    String[] tokens = s.substring(prefix.length()).split("/");
    for (int i=0; i<tokens.length; i++) {
        System.out.println(tokens[i]);
    }
    }

}

String s = "prefix/dir1/dir2/dir3/dir4"

String parts[] = s.split("/");

System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...

If it's a File, you can get the parts by creating an instanceof File and then ask for its segments.

This is good because it'll work regardless of the direction of the slashes; it's platform independent (except for the "drive letters" in windows...)


String.split(String regex) is convenient but if you don't need the regular expression handling then go with the substring(..) example, java.util.StringTokenizer or use Apache commons lang 1. The performance difference when not using regular expressions can be a gain of 1 to 2 orders of magnitude in speed.


 String result;
 String str = "/usr/local/apache2/resumes/dir1/dir2/dir3/dir4";
 String regex ="(dir)+[\\d]";
 Matcher matcher = Pattern.compile( regex ).matcher( str);
  while (matcher.find( ))
  {
  result = matcher.group();     
  System.out.println(result);                 
}

output-- dir1 dir2 dir3 dir4


In this case, why not use new File("prefix/dir1/dir2/dir3/dir4") and go from there?


Using String.split method will surely work as told in other answers here.

Also, StringTokenizer class can be used to to parse the String using / as the delimiter.

import java.util.StringTokenizer;
public class Test
{
    public static void main(String []args)
    {
        String s = "prefix/dir1/dir2/dir3/dir4/..";
        StringTokenizer tokenizer = new StringTokenizer(s, "/");
        String dir1 = tokenizer.nextToken();
        String dir2 = tokenizer.nextToken();
        System.out.println("Dir 1  : "+dir1);
        System.out.println("Dir 2 : " + dir2);
    }
}

Gives the output as :

Dir 1  : prefix
Dir 2 : dir1

Here you can find more about StringTokenizer.