Match all occurrences of a regex

2019-01-03 07:25发布

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.

标签: ruby regex
3条回答
叼着烟拽天下
2楼-- · 2019-01-03 08:03

Using scan should do the trick:

string.scan(/regex/)
查看更多
Luminary・发光体
3楼-- · 2019-01-03 08:12

if you have a regexp with groups :

str="A 54mpl3 string w1th 7 numbers scatter3r ar0und"
re=/(\d+)[m-t]/

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"]
查看更多
仙女界的扛把子
4楼-- · 2019-01-03 08:18

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.

查看更多
登录 后发表回答