Match All Occurrences of a Regex

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.


使用scan应该做的诀窍是:

string.scan(/regex/)

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.


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"]
链接地址: http://www.djcxy.com/p/13404.html

上一篇: 是(非

下一篇: 匹配正则表达式的所有出现次数