【问题标题】:Find a keyword in text and then print words leading up to a separate keyword在文本中查找关键字,然后打印导致单独关键字的单词
【发布时间】:2015-08-29 10:44:17
【问题描述】:

我正在尝试编写一个程序,它查看用户提供的文本,搜索关键字,如果找到该关键字,将打印它以及它后面的任何单词,直到遇到单独的关键字。例如:

  • 搜索"I",打印到"and"
  • 用户文本:"I like fishing and running"
  • 返回:"I like fishing"

我尝试使用each_with_index 遍历用户文本数组,但无法访问当前循环所在单词之前的单词索引。任何访问其他索引的尝试都会返回nil。

def search()
  @text.each_with_index do |word, index|
    if word == "I"
      puts word + word[1]
    end
  end
end

一旦我可以打印未来索引的单词,我的下一个问题将是打印所有导致关键字停止的单词,我想我可以使用if 语句和break 来完成,但我也将不胜感激。

如果您对如何使上述工作有任何建议,或任何其他解决方案,我将不胜感激。

【问题讨论】:

    标签: ruby string


    【解决方案1】:
    str = "The quickest of the quick brown   dogs jumped over the lazy fox"
    word_include = "quick"
    word_exclude = "lazy"
    
    r = /
        \b#{word_include}\b     # match value of word_include between word boundaries 
        .*?                     # match any number of any character, lazily
        (?=\b#{word_exclude}\b) # match value of word_exclude with word breaks
                                # in positive lookahead
        /x                      # extended mode for regex def
      #=> /\bquick\b.*?(?=\blazy\b)/
    
    str[r]
      #=>"quick brown   dogs jumped over the " 
    

    请注意,如果:

    str = "The quick brown lazy dog jumped over the lazy fox"
    

    我们会得到:

    str[r]
      #=> "quick brown "
    

    这就是我们想要的。但是,如果我们将正则表达式中的 .*? 更改为 .*,使其不延迟,我们将获得:

    str[r]
      #=> "quick brown lazy dog jumped over the "
    

    【讨论】:

      【解决方案2】:

      在这里使用索引似乎不是正确的方法。

      _, key, post = "I like fishing and running".partition(/\bI\b/)
      pre, key, _ = (key + post).partition(/\band\b/)
      pre # => "I like fishing"
      

      【讨论】:

      • 一个变种:str.split(/\band\b/).first.split(/(\bI\b)/).last(2).join #=>"I like fishing ".
      • @CarySwoveland 如果要使用split,则应使用2作为第二个参数。
      • 您能详细说明一下吗?在某些情况下需要它还是允许简化?
      • @CarySwoveland 这是为了安全。如果关键字多次出现在字符串中,split不带第二个参数将全部拆分。
      • 我明白了。谢谢。我要么忘记了split 接受了可选的第二个参数,要么从来不知道。我忘了哪个。
      【解决方案3】:
      def enclosed_words(sentence, start_word, end_word)
        words = sentence.split
        return [] unless words.include?(start_word) and words.include?(end_word)
      
        words[words.index(start_word)...words.index(end_word)].join(' ')
      end
      
      enclosed_words('I like fishing and running', 'I', 'and') # => "I like fishing"
      

      【讨论】:

      • 如果两者中的任何一个都不存在,这不会引发错误吗?
      • @JasonMattingly,重写它,使它看起来不会聚集。
      猜你喜欢
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多