2011-05-15 87 views
0

我需要读取一系列行中的文件,然后 根据其中包含 的单词检索特定行。我怎样才能做到这一点?如何仅检索包含特定单词或短语的行?

到目前为止,我看这样行:

lines = File.readlines("myfile.txt") 

现在,我需要扫描包含“红”,“兔子”线,“蓝”。我想尽可能在​​几行代码中完成这部分。

所以,如果我的文件是:

the red queen of hearts. 
yet another sentence. 
and this has no relevant words. 
the blue sky 
the white chocolate rabbit. 
another irrelevant line. 

我想只看到线:

the red queen of hearts. 
the blue sky 
the white chocolate rabbit. 
+0

我想你不想让包含字符串“红”等的行。你想要包含它们的行作为单词。看到我对floatless的答案的评论。 – sawa 2011-05-15 20:30:36

+0

[查找与正则表达式匹配的文本文件中的行]重复(http://stackoverflow.com/questions/6002868/finding-lines-in-a-text-file-matching-a-regular-expression) – Phrogz 2011-05-15 21:33:40

回答

3
lines = File.readlines("myfile.txt").grep(/red|rabbit|blue/) 
+0

This将匹配包括“Fred”,“jackrabbit”,“bluer”的行。正则表达式应该是'/ \ b(?:red | rabbit | blue)\ b /'。 – sawa 2011-05-15 20:28:33

1

正则表达式是你的朋友。他们将迅速完成这项任务。

http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm

你想沿着

/^.*(red|rabbit|blue).*$/ 

^行正则表达式是指线的开始,.*手段匹配任何(red|rabbit|blue)意味着什么,你认为它的意思,最后是$表示行结束。

0

我觉得每一个循环的话最好在这种情况下:

lines.each do |line| 
    if line.include? red or rabbit or blue 
     puts line 
    end 
end 

把那一个镜头。

相关问题