2012-11-27 20 views
5

這應該是一個簡單的問題,但我找不到任何關於它的任何內容。在Ruby中查找多個正則表達式匹配的模式和位置​​

鑑於Ruby中的正則表達式,對於每一個匹配我需要檢索匹配的模式$1,$2,但我也需要匹配的位置。

我知道=~運營商給我第一場比賽的位置,而string.scan(/regex/)給了我所有的匹配模式。如果可能的話,我需要兩個結果在同一個步驟。

回答

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

真棒!謝謝! – Emyl

2

可將掃描範圍內獲取匹配的數據是這樣的:

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