提取句子/字符串中的最后一个单词?

16
我有一个字符串数组,这些字符串的长度和内容各不相同。现在我想要一种简便的方法从每个字符串中提取最后一个单词,而不用知道该单词的长度或该字符串的长度。类似于:
array.each{|string| puts string.fetch(" ", last)
6个回答

36

这应该能正常工作

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

要排除标点符号,删除

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

从数组中获取最后一个元素,你需要使用collect方法,将其转换为数组。

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

1
我想补充一下,你可以向split函数提供一个分隔符。默认情况下,该函数使用空格作为分隔符,但你可能希望在其他字符上进行分割,比如斜杠或破折号。参考:http://ruby-doc.org/core-2.2.0/String.html#method-i-split - Jeroen Bouman

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
所有这些解决方案的问题在于只考虑空格作为单词分隔符。使用正则表达式,您可以捕获任何非单词字符作为单词分隔符。以下是我使用的方法:
str = 'Non-space characters, like foo=bar.'
str.split(/\W/).last
# "bar"

1

"a string of words!".match(/(.*\s)*(.+)\Z/)[2] #=> 'words!' 从最后一个空格开始匹配,包括标点符号。

要从字符串数组中提取它,请与 collect 一起使用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接