how to parse this string in java?


how to parse the dir1,dir2 .. value out of the above string in JAVA?

The prefix here can be : /usr/local/apache2/resumes

-------------Problems Reply------------

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)




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)

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



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.

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

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 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 =;

output-- dir1 dir2 dir3 dir4

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

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++) {


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 str = "bla!/bla/bla/"

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

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

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

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

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

Category:java Views:0 Time:2009-06-04
Tags: string java

Related post

  • What is an efficient way to parse a String in Java? 2009-07-29

    How should I parse the following String using Java to extract the file path? ? stands for any number of random charaters _ stands for any number of white spaces (no new line) ?[LoadFile]_file_=_"foo/bar/baz.xml"? Example: 10:52:21.212 [LoadFile] file

  • Parsing integer strings in Java 2011-04-08

    Possible Duplicate: How to convert a hexadecimal string to long in java? I know that Java can't handle this: Integer.parseInt("0x64") Instead you have to do this: Integer.parseInt("64", 16) Is there something built into Java that can automatically pa

  • Android - parsing JSON strings in Java 2011-05-27

    I've got a JSON string and I'm just trying to access the different properties of it and store them in Java variables. However, I keep getting an exception with the following code: private JSONObject jObj; private String jString; //... jString = resul

  • Parse JSON string in Java 2011-12-02

    I'm trying to parse a JSON string in Java but I cant figure out how! I'm using lib-JSON right now: import net.sf.json.*; . String jsonStr = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}"; JSONObject jsonObj = (JSONObject) JSONSeria

  • How to parse a String into Java Tree? 2012-02-20

    I have a method that generates pop-up menu with many submenus. Basically these menus given dynamically so I have to have algorithm to handle creating submenus using below string. In order to do it I will need to transform this string into Java Tree b

  • Problem when parsing xml string in java 2011-06-30

    I'm writing an android application, and I would like to get an xml string from web and get all info it contains. First of all, i get the string (this code works): URL url = new URL("here my adrress"); BufferedReader reader = new BufferedReader(new In

  • parsing html string in java using regex 2011-11-04

    Need help in parsing html string String str = "<div id=\"test\" ><a href=\"#aaaa\"> Amrit </a> </div><div><a href=\"#bbbb\" > Amrit </a> </div><a href=\"#cccc\" ><a href=\"#dddd\" >"; String

  • Parse a string in Java 2011-11-05

    I have strings formatted similar to the one below in a Java program. I need to get the number out. Host is up (0.0020s latency). I need the number between the '(' and the 's' characters. E.g., I would need the 0.0020 in this example. --------------So

  • Gson : parsing json string to java arraylist like modeling 2014-08-08

    I tried to parse a Json response I guet from my limesurvey server to Java, however I don't see what type of Class I should create it. Here is the json string that I want to parse into a java object : {"id":1,"result":{"gid":"1","type":"L","help":"Veu

  • unable to parse json string using java script eval function 2010-06-22

    I am facing issue with the following Json reponse object in the javascript eval function;Getting java script error expected } because of special characters Tamás and Török {[{"userFirstNm":"Naresh","userAsscId":"70336","userLastNm":"Yashwantrao","use

  • How to parse a string in Java? Is there anything similar to Python's re.finditer()? 2010-09-19

    I have an input string with a very simple pattern - capital letter, integer, capital letter, integer, ... and I would like to separate each capital letter and each integer. I can't figure out the best way to do this in Java. I have tried regexp using

  • Parse this string in Java 2011-10-15

    i'm new to Java . How can i obtain right values of each line (second value of the dash separated pair) Autorul-Stefan DenumireaCartii-Popovici CuloareaCartii-Verde GenulCartii-Religie Limba-Rusa SOLVED : String line = "Autorul-Stefan"; String [] fiel

  • Best way to parse an XML String in Java? 2009-10-05

    I am parsing a string in Java using javax.xml.parsers.DocumentBuilder. However, there is not a function to parse a String directly, so I am instead doing this: public static Document parseText(String zText) { try { DocumentBuilderFactory dbFactory =

  • Parsing HTTP query string in Java 2011-02-06

    Possible Duplicates: Query String Manipulation in Java Parsing query strings in Java I have a string similar to name1=value&name2=value&name3=value. I need to parse this into a map of some sort so I can get at the individual values. I've been

  • In Java, how do I parse a string bigger than int size 2012-02-29

    I have a string bigger than 2,147,483,647 and I need to parse it. Integer.parseInt doesn't do they job, it throws an exception. --------------Solutions------------- Integer.parseInt couldn't do the job, unless you were happy to lose data. Think about

  • Parsing query strings on Android 2009-11-03

    Java EE has ServletRequest.getParameterValues(). On non-EE platforms, URL.getQuery() simply returns a string. What's the normal way to properly parse the query string in a URL when not on Java EE? <rant> It is popular in the answers to try and

  • Parsing a string containing escaped characters using Java 2009-05-10

    Hello I wonder if someone could help me figure out how to parse a string having the following format: ;field1-field2-fieldN;field1-field2-fieldN; Each record is delimited by ';' and each field within a record is delimited by '-'. The complication is

  • Parse number with positive/negative prefix from string in java 2010-01-18

    It's quite straight forward in java to parse number from String, i.e. with Integer.parseInt(s) if string in the format 'n' or '-n', but unfortunately it fails to parse string in the format of '+n'. So what is the most effective/elegant way to parse n

  • How to parse a string into a 2010-09-23

    Hi i am trying to parse a string into a Here is what i am doing private static SimpleDateFormat sdfout = new SimpleDateFormat(""); try{ String date = "2010."; task.setDueDate(new java.sql.Date(sdfout.parse(dat

Copyright (C), All Rights Reserved.

processed in 0.137 (s). 11 q(s)