Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to Python’s findall() method in Ruby?

Tags:

python

regex

ruby

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?

like image 786
gustavgans Avatar asked Jan 23 '23 11:01

gustavgans


1 Answers

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.

like image 92
Daniel Vandersluis Avatar answered Feb 02 '23 08:02

Daniel Vandersluis