这应该是一个简单的问题,但我找不到任何相关信息。
给定一个 Ruby 中的正则表达式,对于每个匹配项,我需要检索匹配的模式 $1
、$2
,但我还需要匹配位置。
我知道 =~
运算符为我提供了第一个匹配项的位置,而 string.scan(/regex/)
为我提供了所有匹配模式。如果可能,我需要在同一步骤中获得两个结果。
最佳答案
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
关于ruby - 在 Ruby 中查找多个正则表达式匹配的模式和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589460/