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

时间:2012-11-27 17:14:12

标签: ruby regex

这应该是一个简单的问题,但我找不到任何相关内容。

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

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

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:2)

您可以像这样访问扫描中的匹配数据:

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