For example:
"Angry Birds 2.4.1".split(" ", 2) => ["Angry", "Birds 2.4.1"]
How can I split the string into: ["Angry Birds", "2.4.1"]
To split a string on the last occurrence of a substring:, use the lastIndexOf() method to get the last index of the substring and call the slice() method on the string to get the portions before and after the substring you want to split on.
Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .
Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
String#rpartition, e.g.
irb(main):068:0> str = "Angry Birds 2.4.1" => "Angry Birds 2.4.1" irb(main):069:0> str.rpartition(' ') => ["Angry Birds", " ", "2.4.1"]
Since the returned value is an array, using .first and .last would allow to treat the result as if it was split in two, e.g
irb(main):073:0> str.rpartition(' ').first => "Angry Birds" irb(main):074:0> str.rpartition(' ').last => "2.4.1"
I hava a solution like this:
class String def split_by_last(char=" ") pos = self.rindex(char) pos != nil ? [self[0...pos], self[pos+1..-1]] : [self] end end "Angry Birds 2.4.1".split_by_last #=> ["Angry Birds", "2.4.1"] "test".split_by_last #=> ["test"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With