Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into only two parts, by the last occurrence of the split char?

Tags:

ruby

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"]

like image 492
ohho Avatar asked Aug 30 '12 07:08

ohho


People also ask

How do you split the last character of a string?

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.

How do you split a string on the last occurrence of a character in python?

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 .

How do you split a string into two parts in Python?

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.


2 Answers

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" 
like image 77
Vadym Tyemirov Avatar answered Sep 25 '22 10:09

Vadym Tyemirov


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"] 
like image 38
halfelf Avatar answered Sep 21 '22 10:09

halfelf