Need to extract from string together with line reference number
My problem is I have a very large file, an example:
f = %q(1:9- The cost of\n
51:10- The beams cost so much\n
41:11- Should we buy more beams\n
21:12- Why buy more}
What I need to do is, as an example, is extract every beams word from any line that contains that particular word. But each beams word must come with the reference for the开发者_Go百科 line it comes from, like this:
51:10 beams\n
41:11 beams\n
Any help is gratefully appreciated.
/(\d{2,2}:\d{2,2})-.*?(beams)/
The first capture will contain the line reference and the second the word beams
You can extract using scan
:
f.scan(/^(\d+\:\d+).+?(beams)/)
=> [["51:10", "beams"], ["41:11", "beams"]]
And for the output:
f.scan(/^(\d+\:\d+).+?(beams)/).each do |pair|
puts pair.join(" ")
end
=>
51:10 beams
41:11 beams
精彩评论