加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby Regex:获取捕获索引

发布时间:2020-12-17 03:55:17 所属栏目:百科 来源:网络整理
导读:我已经看到这个问题并回答了 for javascript regex,答案很长很难看.好奇,如果有人有更清洁的方式在ruby中实现. 这是我想要实现的目标: 测试字符串:“foo bar baz” 正则表达式:/.*(foo).*(bar).*/ 预期回报:[[0,2],[4,6]] 所以我的目标是能够运行一个方
我已经看到这个问题并回答了 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,6]]
# => [[0,6],[8,10]]

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读