5

I need to extract all MP3 titles from a fuzzy list in a list.

With Python this works for me fine:

import re
for i in re.compile('mmc.+?mp3').findall(open("tracklist.txt").read()): print i

How can I do that in Ruby?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
gustavgans
  • 5,141
  • 13
  • 41
  • 51

3 Answers3

7
f = File.new("tracklist.txt", "r")
s = f.read
s.scan(/mmc.+?mp3/) do |track|
  puts track
end

What this code does is open the file for reading and reads the contents as a string into variable s. Then the string is scanned for the regular expression /mmc.+?mp3/ (String#scan collects an array of all matches), and prints each one it finds.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
3

I don't know python very well, but it should be

File.read("tracklist.txt").matches(/mmc.+?mp3/).to_a.each { |match| puts match }

or

File.read("tracklist.txt").scan(/mmc.+?mp3/) { |match| puts match }
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
0

even more simply:

puts File.read('tracklist.txt').scan /mmc.+?mp3/
pguardiario
  • 53,827
  • 19
  • 119
  • 159