我已经看到了这个问题,并回答了javascript正则表达式,答案很长很难看.好奇,如果有人有更清洁的方式在ruby中实现.
这是我想要实现的目标:
测试字符串:正则 "foo bar baz"
表达式: /.*(foo).*(bar).*/
预期回报: [[0,2],[4,6]]
所以我的目标是能够运行一个方法,传入测试字符串和正则表达式,它将返回每个捕获组匹配的索引.我在预期回报中包含了捕获组的起始和结束索引.我将继续努力,并在此过程中添加我自己的潜在解决方案.当然,如果除了正则表达式之外还有一种更清洁/更容易实现的方法,那也是一个很好的答案.
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)
像这样的东西应该适用于一般的比赛.
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
| 归档时间: |
|
| 查看次数: |
1774 次 |
| 最近记录: |