gpt4 book ai didi

ruby 正则表达式 : Get Index of Capture

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:52 25 4
gpt4 key购买 nike

我看过这个问题的问答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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com