我正在尝试编写一个程序来查看用户提供的文本,搜索关键字,如果找到该关键字,将打印它以及它后面的任何单词,直到遇到单独的关键字。例如:
- 搜索
"I"
,打印直到"and"
- 用户文本:
“我喜欢钓鱼和运行”
- 返回:
“我喜欢钓鱼”
我曾尝试使用 each_with_index
遍历用户文本数组,但无法访问当前循环所在单词之前的单词索引。任何访问其他索引的尝试都会返回 nil
。
def search()
@text.each_with_index do |word, index|
if word == "I"
puts word + word[1]
end
end
end
一旦我可以打印 future 索引的单词,我的下一个问题就是打印导致一个告诉它停止的关键字的所有单词,我想我可以用 if
语句和 break
,但我也很感激对此有任何想法。
如果您对如何使上述工作有任何建议,或任何其他解决方案,我将不胜感激。
最佳答案
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 "
关于ruby - 在文本中查找关键字,然后打印导致单独关键字的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32280927/