在文本中查找关键字,然后打印导致单独关键字的单词

时间:2015-08-28 22:57:35

标签: ruby string

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

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

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

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

一旦我可以打印未来索引的单词,我的下一个问题就是打印所有单词,直到一个关键词告诉它停止,我想我可能会用if语句和{ {1}},但我也很感激任何想法。

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

3 个答案:

答案 0 :(得分:2)

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 "

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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"