ruby 正则表达式 : Get Index of Capture

标签 ruby regex

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

相关文章:

ruby-on-rails - 包含没有 include 语句的 ruby​​ 模块 - 这是如何实现的?

ruby - 将类的 Ruby 数组转换为 JSON

ruby-on-rails - 如何测试变量未定义或RSpec中引发异常

javascript - StartsWith 在每个单词的基础上进行匹配。被视为 AND 运算符的空间

ruby-on-rails - 你如何在 Rails 4 中存储自定义常量?

ruby-on-rails - "if"条件出现问题

c++ - 在正则表达式中捕获重复组

PHP preg_match() 匹配字符串末尾的字符

javascript - 正则表达式 : Allow only use of a few words and only once per word

ruby - 可扩展的自托管文件上传到 Ruby on Rails