2015-08-28 30 views
1

我正在嘗試編寫一個程序,用於查看用戶提供的文本,搜索關鍵字,如果它找到該關鍵字,則會將其打印爲以及跟隨它的任何單詞,直到遇到單獨的關鍵字。例如:在文本中查找關鍵字,然後打印導致單獨關鍵字的單詞

  • 搜索"I",打印,直到"and"
  • 用戶文本:"I like fishing and running"
  • 返回:通過使用each_with_index的用戶的文本的陣列"I like fishing"

我試圖循環,但無法訪問我的循環當前所處的單詞之前的單詞索引。任何訪問其他指數的嘗試都會返回nil

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

有一次,我可以打印未來指數的話,我的下一個問題將是印刷領導到一個關鍵的詞,告訴它停下來,我想我可以或許與if聲明和break做的所有的話,但我也很樂意爲此提供任何想法。

如果您對如何進行上述工作或任何其他解決方案有任何建議,我將不勝感激。

回答

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

在這裏使用索引似乎並不正確。

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

的變體:'str.split(/ \帶\ B /)first.split(/( \ bI \ b)/)。last(2).join#=>「我喜歡釣魚」。 –

+0

@CarySwoveland如果使用'split',它應該與'2'一起用作第二個參數。 – sawa

+0

你能詳細說明一下嗎?在某些情況下需要還是允許簡化? –

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" 
+0

如果兩者中的任何一個都不存在,這不會引發錯誤嗎? – JasonMattingly

+0

當然,它不會保留間距。 –

+0

@JasonMattingly,重寫它,所以它不會看起來羣集。 – ndn

相關問題