2012-03-02 129 views
11

我有一串不同長度和內容的字符串。提取句子/字符串中的最後一個單詞?

現在我正在尋找一種簡單的方法來從每個字符串中提取最後一個單詞,而無需知道該單詞的長度或字符串的長度。

類似的東西;

array.each{|string| puts string.fetch(" ", last) 

回答

26

這應該只是罰款

"my random sentence".split.last # => "sentence" 

排除標點符號,delete

"my rando­m sente­nce..,.!?".­split.last­.delete('.­!?,') #=> "sentence" 

從陣列獲取的 「遺言」 作爲數組你collect

["random sentence...",­ "lorem ipsum!!!"­].collect { |s| s.spl­it.last.delete('.­!?,') } # => ["sentence", "ipsum"] 
+0

完美,我在正確的軌道上。謝謝! – BSG 2012-03-02 13:44:22

+1

我想補充說,你可以提供一個分隔符到分割函數。該函數默認使用空格,但是你可能想要分割別的東西,比如斜槓或破折號。參考:http://ruby-doc.org/core-2.2.0/String.html#method-i-split – 2016-06-09 05:47:11

3
array_of_strings = ["test 1", "test 2", "test 3"] 
array_of_strings.map{|str| str.split.last} #=> ["1","2","3"] 
1
["one two",­ "thre­e four five"­].collect { |s| s.spl­it.last } 
=> ["two", "five"] 
1

"a string of words!".match(/(.*\s)*(.+)\Z/)[2] #=> 'words!'從最後一個空白處捕獲。這將包括標點符號。

若要提取從字符串數組,以收集使用它:

["a string of words", "Something to say?", "Try me!"].collect {|s| s.match(/(.*\s)*(.+)\Z/)[2] } #=> ["words", "say?", "me!"]

0

這是我能想到的最簡單的方法。

hostname> irb 
irb(main):001:0> str = 'This is a string.' 
=> "This is a string." 
irb(main):002:0> words = str.split(/\s+/).last 
=> "string." 
irb(main):003:0> 
相關問題