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
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);
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("/");
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);
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.