string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. "
d = string.match(/(jack|jill)/i) # -> MatchData "Jill" 1:"Jill"
d.size # -> 1
这只匹配它出现的第一次出现。
string.scan
部分完成了这项工作,但它没有说明匹配模式的索引。
如何获得模式及其索引(位置)的所有匹配实例的列表?
答案 0 :(得分:20)
您可以使用.scan
和$`
全局变量,这意味着上一次成功匹配项左侧的字符串,但它在通常{{}内部不起作用1}},所以你需要这个 hack (从this answer偷来):
.scan
输出:
string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. "
string.to_enum(:scan, /(jack|jill)/i).map do |m,|
p [$`.size, m]
end
<强> UPD:强>
注意lookbehind的行为 - 你得到真正匹配的部分的索引,而不是看起来一个:
[0, "Jack"]
[9, "Jill"]
[57, "Jack"]
[97, "Jill"]
答案 1 :(得分:1)
如果您只想提供&#34; Jack&#34;的位置,那么这是对Nakilon答案的修改。成阵列
location_array = Array.new
string = "Jack and Jack went up the hill to fetch a pail of Jack..."
string.to_enum(:scan,/(jack)/i).map do |m,|
location_array.push [$`.size]
end