How do I get the match data for all occurrences of a Ruby regular expression in a string?

You want

"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }

which gives you

[#<MatchData "12">, #<MatchData "34">, #<MatchData "567">] 

The “trick” is, as you see, to build an enumerator in order to get each last_match.

Leave a Comment