Ruby Regex:获取捕获索引

Jef*_*nte 4 ruby regex

我已经看到了这个问题,并回答了javascript正则表达式,答案很长很难看.好奇,如果有人有更清洁的方式在ruby中实现.

这是我想要实现的目标:

测试字符串:正则 "foo bar baz"
表达式: /.*(foo).*(bar).*/
预期回报: [[0,2],[4,6]]

所以我的目标是能够运行一个方法,传入测试字符串和正则表达式,它将返回每个捕获组匹配的索引.我在预期回报中包含了捕获组的起始和结束索引.我将继续努力,并在此过程中添加我自己的潜在解决方案.当然,如果除了正则表达式之外还有一种更清洁/更容易实现的方法,那也是一个很好的答案.

saw*_*awa 5

m = "foo bar baz".match(/.*(foo).*(bar).*/)
[1, 2].map{|i| [m.begin(i), m.end(i) - 1]}
# => [[0, 2], [4, 6]]
Run Code Online (Sandbox Code Playgroud)

  • 这太棒了 - 很棒的答案,很快!困扰我的唯一问题是地图开头的数组,必须手动设置以匹配捕获组的数量.也许这样的事情可以解决这个问题?`1.upto(m.size-1).to_a.map {| I | [m.begin(i),m.end(i) - 1]}` (2认同)

Tal*_*Tal 5

像这样的东西应该适用于一般的比赛.

def match_indexes(string, regex)
  matches = string.match(regex)

  (1...matches.length).map do |index|
    [matches.begin(index), matches.end(index) - 1]
  end
end

string = "foo bar baz"

match_indexes(string, /.*(foo).*/)
match_indexes(string, /.*(foo).*(bar).*/)
match_indexes(string, /.*(foo).*(bar).*(baz).*/)
# => [[0, 2]]
# => [[0, 2], [4, 6]]
# => [[0, 2], [4, 6], [8, 10]]
Run Code Online (Sandbox Code Playgroud)

你可以看一下(有点奇怪的)MatchData类,看看它是如何工作的.http://www.ruby-doc.org/core-1.9.3/MatchData.html