开发者

How do I retrieve only lines with specific words or phrases?

I need to read a file in a series of lines, and then retrieve specific lines depending on words that are contained in them. How can I do this?

So far I read the lines like this:

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

No开发者_开发问答w, I need to scan for lines that contain "red", "rabbit", "blue". I want to do this part in as few lines of code as possible.

So if my file was:

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

I would like to see only the lines:

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


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


Regular expressions are your friend. They will make quick work of this task.

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

You would want a regex along the lines of

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

The ^ means start of line, the .* means match anything, (red|rabbit|blue) means exactly what you think it means, and lastly the $ means end of line.


I think an each loop would be best in this situation:

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

Give that a shot.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜