2013-03-07 45 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' 
相關問題