【问题标题】:Extract the last word in sentence/string?提取句子/字符串中的最后一个单词?
【发布时间】:2012-03-21 00:19:50
【问题描述】:

我有一个不同长度和内容的字符串数组。

现在我正在寻找一种简单的方法来从每个字符串中提取最后一个单词,而不知道该单词有多长或字符串有多长。

类似的东西;

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

【问题讨论】:

    标签: ruby string substring text-segmentation


    【解决方案1】:

    这应该可以正常工作

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

    排除标点符号,deleteit

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

    要从您collect的数组中获取“最后一句话”作为数组

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

    【讨论】:

    【解决方案2】:
    array_of_strings = ["test 1", "test 2", "test 3"]
    array_of_strings.map{|str| str.split.last} #=> ["1","2","3"]
    

    【讨论】:

      【解决方案3】:
      ["one two",­ "thre­e four five"­].collect { |s| s.spl­it.last }
      => ["two", "five"]
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          所有这些解决方案的问题在于您只考虑空格来分隔单词。使用正则表达式,您可以捕获任何非单词字符作为单词分隔符。这是我使用的:

          str = 'Non-space characters, like foo=bar.'
          str.split(/\W/).last
          # "bar"
          

          【讨论】:

            【解决方案6】:

            这是我能想到的最简单的方法。

            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> 
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-01-17
              • 1970-01-01
              • 2021-12-23
              • 1970-01-01
              • 1970-01-01
              • 2013-09-07
              相关资源
              最近更新 更多