scan - ruby string match regex




Match all occurrences of a regex (2)

Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.


For finding all the matching strings, Use scan method of String class.

str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
str.scan(/\d+/)
#=> ["54", "3", "1", "7", "3", "36", "0"]

If you rather want MatchData which is the type of the object returned by, match method of Regexp classs, use the following

str.to_enum(:scan, /\d+/).map { Regexp.last_match }
#=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]

The benefit of having MatchData is that you can use methods like offset

match_datas = str.to_enum(:scan, /\d+/).map { Regexp.last_match }
match_datas[0].offset(0)
#=> [2, 4]
match_datas[1].offset(0)
#=> [7, 8]

Refer these questions too if you'd like to know more
How do I get the match data for all occurrences of a Ruby regular expression in a string?
Ruby regular expression matching enumerator with named capture support
How to find out the starting point for each match in ruby

Reading about special variables $&, $', $1, $2 in ruby will be super helpful.


Using scan should do the trick:

string.scan(/regex/)






regex