3

I'd like to parse a string so I can build an XML document.

I have:

String value = "path=/Some/Xpath/Here";

I've parsed it this way:

private void parseXpath() {
    String s = "path=/Some/Xpath/Here";

    String[] tokens = s.split("/");
    for(String t: tokens){
        System.out.println(t);
    }
}

output:

path=
Some
Xpath
Here

How can I remove "path=" altogether? I want just the values from xpath?

Edit:

Thanks for the responses.

How can I make this method into one which returns String[],

Example:

private String[] parseXpath(String s) {

String[] tokens = s.replaceFirst(".*=", "").split("/");
   for(String t: tokens){
      System.out.println(t);
   }
   return tokens;
}

My output is:

[Ljava.lang.String;@413849df

How can I make it return me array of strings?

mosawi
  • 1,283
  • 5
  • 25
  • 48
  • 2
    it already returns a array of string, but you cant just throw it into System.out.println(...); that would just print its object-id. you need to iterate the array to print its contents – ChrisKo Aug 12 '15 at 18:34
  • Or use `System.out.println( Arrays.toString( arr ) )`. – RealSkeptic Aug 12 '15 at 18:37

4 Answers4

6

Just do replace before splitting.

String[] tokens = s.replaceFirst(".*=", "").split("/");

This would give you an empty element at first because it would do splitting on the first forward slash after replacing.

or

String[] tokens = s.replaceFirst(".*=/", "").split("/");

But if you remove all the chars upto the = along with the first forward slash will give you the desired output.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
3

Although the question is tagged with regex here is a solution using substring

    String[] tokens = s.substring(s.indexOf("=") + 1).split("/");

or

    String[] tokens = s.substring(s.indexOf("=/") + 1).split("/");
Ashraf Purno
  • 1,065
  • 6
  • 11
2

Try with:

private void parseXpath() {
    String s = "path=/Some/Xpath/Here";
    s = s.replace("path=","");

    String[] tokens = s.split("/");
    for(String t: tokens){
        System.out.println(t);
    }
}

Also you can avoid removing it at all, if you get path=/Some/Xpath/Here by other regex, use lookbehind instead of exact matching:

(?<=path=)[^\\,]*

you should get just /Some/Xpath/Here.

EDIT If you want to print array as String, use static method Arrays.toString(yourArray);

m.cekiera
  • 5,365
  • 5
  • 21
  • 35
1

if you are looking into performance you should avoid usage of split since it uses regular-expressions which is a bit oversized for such a simple problem. if you just want to remove "path=" and you are sure that your string always starts that way you could go with the following:

String s = "path=/Some/Xpath/Here";
String prefix = "path=";
String result = s.substring(prefix.length);
ChrisKo
  • 365
  • 2
  • 8