Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optionally using String.split(), split a string at the last occurance of a delimiter

I have a string that matches this regular expression: ^.+:[0-9]+(\.[0-9]+)*/[0-9]+$ which can easily be visualized as (Text):(Double)/(Int). I need to split this string into the three parts. Normally this would be easy, except that the (Text) may contain colons, so I cannot split on any colon - but rather the last colon.

The .* is greedy so it already does a pretty neat job of doing this, but this wont work as a regular expression into String.split() because it will eat my (Text) as part of the delimiter. Ideally I'd like to have something that would return a String[] with three strings. I'm 100% fine with not using String.split() for this.

like image 345
Huckle Avatar asked Jun 07 '12 21:06

Huckle


People also ask

How do you split at last delimiter?

Use the str. rsplit() method with maxsplit set to 1 to split a string on the last occurrence of a delimiter, e.g. my_str. rsplit(',', 1) . The rsplit() method splits from the right, and only performs a single split when maxsplit is set to 1 .

How do you split a string with a delimiter?

Using String. split() Method. The split() method of the String class is used to split a string into an array of String objects based on the specified delimiter that matches the regular expression.

How do you split the last element of a string?

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.

How do you get the last string of a split in Python?

Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element.


1 Answers

I don't like regex (just kidding I do but I'm not very good at it).

String s = "asdf:1.0/1"
String text = s.substring(0,s.lastIndexOf(":"));
String doub = s.substring(s.lastIndexOf(":")+1,text.indexOf("/"));
String inte = s.substring(text.indexOf("/")+1,s.length());
like image 116
tskuzzy Avatar answered Sep 20 '22 17:09

tskuzzy