How to parse this string in Java?

前端 未结 10 1337
感情败类
感情败类 2020-11-29 05:19

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

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

The prefix here c

相关标签:
10条回答
  • 2020-11-29 05:43

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

    0 讨论(0)
  • 2020-11-29 05:45
     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

    0 讨论(0)
  • 2020-11-29 05:47

    If you want to split the String at the / character, the String.split method will work:

    For example:

    String s = "prefix/dir1/dir2/dir3/dir4";
    String[] tokens = s.split("/");
    
    for (String t : tokens)
      System.out.println(t);
    

    Output

    prefix
    dir1
    dir2
    dir3
    dir4
    

    Edit

    Case with a / in the prefix, and we know what the prefix is:

    String s = "slash/prefix/dir1/dir2/dir3/dir4";
    
    String prefix = "slash/prefix/";
    String noPrefixStr = s.substring(s.indexOf(prefix) + prefix.length());
    
    String[] tokens = noPrefixStr.split("/");
    
    for (String t : tokens)
      System.out.println(t);
    

    The substring without the prefix "slash/prefix/" is made by the substring method. That String is then run through split.

    Output:

    dir1
    dir2
    dir3
    dir4
    

    Edit again

    If this String is actually dealing with file paths, using the File class is probably more preferable than using string manipulations. Classes like File which already take into account all the intricacies of dealing with file paths is going to be more robust.

    0 讨论(0)
  • 2020-11-29 05:50
    String s = "prefix/dir1/dir2/dir3/dir4"
    
    String parts[] = s.split("/");
    
    System.out.println(s[0]); // "prefix"
    System.out.println(s[1]); // "dir1"
    ...
    
    0 讨论(0)
  • 2020-11-29 05:52
    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]);
        }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 05:53
    ...
    String str = "bla!/bla/bla/"
    
    String parts[] = str.split("/");
    
    //To get fist "bla!"
    String dir1 = parts[0];
    
    0 讨论(0)
提交回复
热议问题