2011-03-09 66 views
23

位置(S)我想匹配正則表達式,並拿到賽紅寶石正則表達式:匹配並獲得

例如在字符串中的位置,

"AustinTexasDallasTexas".match_with_posn /(Texas)/ 

我想match_with_posn返回類似於:[6, 17]其中6和17是德克薩斯單詞的兩個實例的起始位置。

有沒有這樣的事情?

+0

可能重複[如何獲得所有出現的指標在一個字符串中的模式](http://stackoverflow.com/questions/4274388/how-to-get-indexes-of-all-occurrences-of-a-pattern-in-a-string) – Nakilon 2015-09-11 12:51:06

回答

43

使用Ruby 1.8.6+,你可以這樣做:

require 'enumerator' #Only for 1.8.6, newer versions should not need this. 

s = "AustinTexasDallasTexas" 
positions = s.enum_for(:scan, /Texas/).map { Regexp.last_match.begin(0) } 

這將創建一個數組:

=> [6, 17] 
+0

如果你想在Isateateatest中找到atea,它將返回[2],但是5也是一種可能性 – adcosta 2014-12-26 17:18:17

+2

索引5中的「a」用於匹配在索引2處找到的「atea」。如果搜索「ate」 ,你會得到一個'[2,5,8]'的數組。如果你想查找重疊匹配,那麼使用一個前瞻斷言:'/(?=(atea))/'。 'positions = s.enum_for(:scan,/(?=(atea))/).map {Regexp.last_match.begin(0)}#=> [2,5]' – 2014-12-26 17:47:11

+0

請投票的人請投票解釋倒票? – 2015-03-03 20:25:35

24

排序,請參閱String#index

"AustinTexasDallasTexas".index /Texas/ 
=> 6 

現在,你可以擴展字符串的API。

class String 
    def indices e 
    start, result = -1, [] 
    result << start while start = (self.index e, start + 1) 
    result 
    end 
end 
p "AustinTexasDallasTexas".indices /Texas/ 
=> [6, 17] 
+0

作品像一個魅力!太好了! – Tilo 2015-03-03 19:25:09