在Ruby中找到多个正则表达式匹配的模式和位置

这应该是一个简单的问题,但我找不到任何关于它的信息。

给定Ruby中的正则表达式,对于每个匹配我需要检索匹配的模式$1$2 ,但我还需要匹配的位置。

我知道=~运算符给了我第一个匹配的位置,而string.scan(/regex/)给了我所有匹配的模式。 如果可能的话,我需要在同一步骤中得到两个结果。

MatchData

 string.scan(regex) do $1 # Pattern at first position $2 # Pattern at second position $~.offset(1) # Starting and ending position of $1 $~.offset(2) # Starting and ending position of $2 end 

您可以在扫描中访问匹配数据,如下所示:

 "abcdefghij".scan(/\w/) {p $~}