2013-03-07 72 views
1

我希望能够将字符串拆分为2个元素,因为每个字符串都至少包含一个分隔符。通过最后一个分隔符分割的轨道

例如:"hello_world"。如果我申请.split("_"),那么我收到:["hello", "world"]

问题出现时,我有一个字符串与两个或多个分隔符。示例"hello_to_you"。 我想收到:["hello_to", "you"]

我知道分割函数的限制选项:.split("_", 2),但它产生:["hello", "to_you"]

所以,基本上,我需要分割整个字符串与最后一个分隔符(“_”)。

+0

同样的问题措辞不同:[红宝石:在字符分割字符串,从右侧计数(HTTP: //sketchoverflow.com/questions/1844118/ruby-split-string-at-character-counting-from-the-right-side) – 2013-03-07 15:56:56

回答

2

尝试

'hello_to_you'.split /\_(?=[^_]*$)/ 
+0

谢谢。干净,简单,工作良好!正是我需要的! – Dmitri 2013-03-07 11:05:09

+1

虽然不要逃避'_'。也不是'/_(?!.*_)/'更容易? – pguardiario 2013-03-07 12:22:31

2
class String 
    def split_by_last_occurrance(char=" ") 
    loc = self.rindex(char) 
    loc != nil ? [self[0...loc], self[loc+1..-1]] : [self] 
    end 
end 

"test by last_occurrance".split_by_last #=> ["test by", "last"] 
"test".split_by_last_occurrance    #=> ["test"] 
+0

谢谢:)应该工作正常 – Dmitri 2013-03-07 11:05:52

+0

不要重新发明轮子,而是看看我的回答 – 2013-03-07 15:52:31

5

这正是String#rpartition做:

first_part, _, last_part = 'hello_to_you'.rpartition('_') 
first_part # => 'hello_to' 
last_part # => 'you'