ruby regex:匹配并获得位置
我想匹配正则表达式并获得匹配字符串中的位置
例如,
"AustinTexasDallasTexas".match_with_posn /(Texas)/
我想match_with_posn
返回类似的东西: [6, 17]
match_with_posn
[6, 17]
其中6和17是德克萨斯这两个实例的起始位置。
有这样的吗?
使用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]
排序,请参阅String#index
"AustinTexasDallasTexas".index /Texas/ => 6
现在,您可以扩展String 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]
"AustinTexasDallasTexas".gsub(/Texas/).map { Regexp.last_match.begin(0) } #=> [6, 17]