我看过这个问题的问答for javascript regex ,答案又长又难看。想知道是否有人有更简洁的方法在 ruby 中实现。
这是我要实现的目标:
测试字符串: "foo bar baz"
正则表达式: /.*(foo).*(bar).*/
预期返回: [[0,2],[4,6]]
所以我的目标是能够运行一个方法,传入测试字符串和正则表达式,这将返回每个捕获组匹配的索引。我在预期返回中包括了捕获组的起始和结束索引。我将致力于此,并在此过程中添加我自己的潜在解决方案。当然,如果有比正则表达式更清洁/更容易实现此目的的方法,那也是一个很好的答案。
最佳答案
像这样的东西应该适用于一般数量的比赛。
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]]
您可以查看(有点奇怪的)MatchData 类以了解其工作原理。 http://www.ruby-doc.org/core-1.9.3/MatchData.html
关于 ruby 正则表达式 : Get Index of Capture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17729934/