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

前端 未结 10 1396
猫巷女王i
猫巷女王i 2020-12-29 01:22

For example:

\"Angry Birds 2.4.1\".split(\" \", 2)
 => [\"Angry\", \"Birds 2.4.1\"] 

How can I split the string into: [\"Angry Bir

相关标签:
10条回答
  • 2020-12-29 01:48

    Something like this maybe ? Split where a space is followed by anything but a space till the end of the string.

    "Angry Birds 2.4.1".split(/ (?=\S+$)/)
    #=> ["Angry Birds", "2.4.1"]
    
    0 讨论(0)
  • 2020-12-29 01:51

    reverse, split, then reverse every element and elements in array

    "Angry Birds 2.4.1".reverse.split(' ', 2).map(&:reverse).reverse
    
    0 讨论(0)
  • 2020-12-29 02:02

    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"
    
    0 讨论(0)
  • 2020-12-29 02:02

    "Angry Birds 2.4.1".split(/ (?=\d+)/)

    0 讨论(0)
提交回复
热议问题