2011-03-09 48 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