53

例えば:

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

文字列を次のように分割するにはどうすればよいですか。["Angry Birds", "2.4.1"]

4

10 に答える 10

11

私はこのような解決策を持っています:

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"]
于 2012-08-30T08:20:57.657 に答える
10

このようなものでしょうか?文字列の末尾まで、スペースの後にスペース以外のものが続く場所で分割します。

"Angry Birds 2.4.1".split(/ (?=\S+$)/)
#=> ["Angry Birds", "2.4.1"]
于 2012-08-30T08:15:07.923 に答える
2

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

于 2012-08-30T08:04:01.167 に答える
1

これはおそらく非常にトリッキーです (そしておそらく特に効率的ではありません) が、次のようにすることができます。

"Angry Birds 2.4.1".reverse.split(" ", 2).map(&:reverse).reverse
于 2012-08-30T09:54:37.243 に答える
0
class String
  def divide_into_two_from_end(separator = ' ')
    self.split(separator)[-1].split().unshift(self.split(separator)[0..-2].join(separator))
  end
end

"Angry Birds 2.4.1".divide_into_two_from_end(' ') #=> ["Angry Birds", "2.4.1"]
于 2012-08-30T08:26:40.623 に答える