Match all occurrences of a regex

Chris Bunch Source

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.



answered 10 years ago Jean #1

Using scan should do the trick:


answered 3 years ago sudo bangbang #2

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

str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
#=> ["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 }
#=> [2, 4]
#=> [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.

answered 2 years ago MVP #3

if you have a regexp with groups :

str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"

You use scan of string method to find matching groups:

str.scan re
#> [["54"], ["1"], ["3"]]

To find matching pattern:

str.to_enum(:scan,re).map {$&}
#> ["54m", "1t", "3r"]

comments powered by Disqus