zzamboni.org

Capturing Multiple Matches in Ruby

To collect all regex matches in a string into an array, pass the regexp object to the string’s scan() method, e.g.: myarray = mystring.scan(/regex/). Sometimes, it is easier to create a regex to match the delimiters rather than the text you are interested in. In that case, use the split() method instead, e.g.: myarray = mystring.split(/delimiter/). The split() method discards all regex matches, returning the text between the matches. The scan() method does the opposite.

If your regular expression contains capturing groups, scan() returns an array of arrays. Each element in the overall array will contain an array consisting of the overall regex match, plus the text matched by all capturing groups.

For me it was not obvious how to emulate Perl’s /g regex modifier in Ruby, to capture all matches in an array, for example. Here’s how you do it, through a method in the String class rather than the Regexp class:
string.scan(/regex/).flatten
The call to flatten just makes it easier to process if regex has capture groups, and you are just interested in the list of matches and not the structure of where they were found.