ruby-如何在最后一次出现分割字符时将字符串分割为两部分?

例如:

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

如何将字符串拆分为:["Angry Birds", "2.4.1"]

ohho asked 2020-07-12T02:11:55Z
8个解决方案
88 votes

字符串#rpartition,例如

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

由于返回的值是一个数组,因此使用.first和.last将允许将结果视为将其分成两部分,例如

irb(main):073:0> str.rpartition(' ').first
=> "Angry Birds"
irb(main):074:0> str.rpartition(' ').last
=> "2.4.1"
Vadym Tyemirov answered 2020-07-12T02:12:14Z
9 votes

我有这样的解决方案:

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"]
halfelf answered 2020-07-12T02:12:34Z
8 votes

像这样的东西?拆分,直到字符串末尾都有空格,后跟空格。

"Angry Birds 2.4.1".split(/ (?=\S+$)/)
#=> ["Angry Birds", "2.4.1"]
oldergod answered 2020-07-12T02:12:54Z
2 votes

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

sumskyi answered 2020-07-12T02:13:09Z
2 votes

这可能太棘手了(并且可能不是特别有效),但是您可以这样做:

"Angry Birds 2.4.1".reverse.split(" ", 2).map(&:reverse).reverse
matthew.tuck answered 2020-07-12T02:13:29Z
2 votes

rpartition解决方案制作了一个很棒的性感单线(我投赞成票),但是如果您想要一种更灵活的衬板来解决更复杂的分区问题,这是另一种技术:

["Angry Birds 2.4.1".split(' ')[0..-2].join(' '), "Angry Birds 2.4.1".split(' ')[-1..-1].join(' ')]

更加灵活,我的意思是,如果要分割的项目更多,则可以调整序列的范围。

jsarma answered 2020-07-12T02:13:54Z
1 votes

我似乎无法以正确的格式设置注释中的示例代码,因此即使Vadym Tyemirov值得他在上文中提供的Array#first解决方案全部功劳,我还是将其作为单独的答案提交。

我只是想补充一点,Array#first与Ruby的“无关”变量可以很好地配合,因为通常您确实只对结果数组的第一个和最后一个元素感兴趣,而对中间元素(分隔符)不感兴趣:

[1] pry(main)> name, _, version = "Angry Birds 2.4.1".rpartition(' ')
=> ["Angry Birds", " ", "2.4.1"]
[2] pry(main)> name
=> "Angry Birds"
[3] pry(main)> version
=> "2.4.1"

因此不需要2962560226479834834或Array#last ...少即是多! :-)

pvandenberk answered 2020-07-12T02:14:24Z
0 votes
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"]
Jing Li answered 2020-07-12T02:14:39Z
translate from https://stackoverflow.com:/questions/12192343/how-to-split-a-string-into-only-two-parts-by-the-last-occurrence-of-the-split-c