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.
Using scan
should do the trick:
string.scan(/regex/)
-
9But what abut this case? "match me!".scan(/.../) = [ "mat", "ch " "me!" ], but all occurrences of /.../ would be [ "mat", "atc", "tch", "ch ", ... ] – Michael Dickens Dec 25 '11 at 23:22
-
13Not it wouldn't be. /.../ is a normal greedy regexp. It won't backtrack on matched content. you could try to use a lazy regexp but even that probably won't be enough. have a look at the regexp doc ruby-doc.org/core-1.9.3/Regexp.html to correctly express your regexp :) – Jean Jan 3 '12 at 15:31
-
52this seems like a Ruby WTF... why is this on String instead of Regexp with the other regexp stuff? It isn't even mentioned anywhere on the docs for Regexp – Anentropic Mar 12 '13 at 11:36
-
9I guess it's because it's defined and called on String not on Regex ... But it does actually make sense. You can write a regular expression to capture all matches using Regex#match and iterate over captured groups. Here you write a partial match function and want it applied mutiple times on a given string, this is not the responsibility of Regexp. I suggest you check the implementation of scan for a better understanding: ruby-doc.org/core-1.9.3/String.html#method-i-scan – Jean Mar 12 '13 at 12:29
-
9
To find all the matching strings, use String's scan
method.
str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
str.scan(/\d+/)
#=> ["54", "3", "1", "7", "3", "36", "0"]
If you want, MatchData
, which is the type of the object returned by the Regexp match
method, use:
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 using 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]
See these questions 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 helpful too.
if you have a regexp with groups:
str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"
re=/(\d+)[m-t]/
you can use String's scan
method to find matching groups:
str.scan re
#> [["54"], ["1"], ["3"]]
To find the matching pattern:
str.to_enum(:scan,re).map {$&}
#> ["54m", "1t", "3r"]
-
str.scan(/\d+[m-t]/) # => ["54m", "1t", "3r"]
is more idiomatic thanstr.to_enum(:scan,re).map {$&}
– the Tin Man Apr 9 '20 at 17:43 -
Maybe you misunderstood. The regular expression of the example of a user I replied was:
/(\d+)[m-t]/
not/\d+[m-t]/
To write:re = /(\d+)[m-t]/; str.scan(re)
is samestr.scan(/(\d+)[mt]/)
but I get #>[["" 54 "], [" 1 "], [" 3 "]]
and not"54m", "1t", "3r"]
The question was: if I have a regular expression with a group and want to capture all the patterns without changing the regular expression (leaving the group), how can I do it? In this sense, a possible solution, albeit a little cryptic and difficult to read, was:str.to_enum(:scan,re).map {$&}
– MVP Apr 15 '20 at 15:43
You can use string.scan(your_regex).flatten
. If your regex contains groups, it will return in a single plain array.
string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
your_regex = /(\d+)[m-t]/
string.scan(your_regex).flatten
=> ["54", "1", "3"]
Regex can be a named group as well.
string = 'group_photo.jpg'
regex = /\A(?<name>.*)\.(?<ext>.*)\z/
string.scan(regex).flatten
You can also use gsub
, it's just one more way if you want MatchData.
str.gsub(/\d/).map{ Regexp.last_match }
-
Remove the grouping from
your_regex = /(\d+)[m-t]/
and you won't need to useflatten
. Your final example useslast_match
which in this case is probably safe, but is a global and could possibly be overwritten if any regex was matched prior to callinglast_match
. Instead it's probably safer to usestring.match(regex).captures # => ["group_photo", "jpg"]
orstring.scan(/\d+/) # => ["54", "3", "1", "7", "3", "0"]
as shown in other answers, depending on the pattern and needs. – the Tin Man Apr 9 '20 at 17:23