【问题标题】:Ruby Regex: Get Index of CaptureRuby Regex:获取捕获索引
【发布时间】:2013-07-17 18:51:11
【问题描述】:

我看到这个问题被问和回答for javascript regex,答案又长又丑。好奇是否有人有更清洁的方式在 ruby​​ 中实现。

这是我想要达到的目标:

测试字符串: "foo bar baz"
正则表达式: /.*(foo).*(bar).*/
预期返回: [[0,2],[4,6]]

所以我的目标是能够运行一个方法,传入测试字符串和正则表达式,这将返回每个捕获组匹配的索引。我已将捕获组的起始和结束索引都包含在预期收益中。我将继续努力,并在此过程中添加我自己的潜在解决方案。当然,如果除了正则表达式之外还有一种更清洁/更容易实现这一目标的方法,那也是一个很好的答案。

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    这样的东西应该适用于一般数量的匹配。

    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

    【讨论】:

      【解决方案2】:
      m = "foo bar baz".match(/.*(foo).*(bar).*/)
      [1, 2].map{|i| [m.begin(i), m.end(i) - 1]}
      # => [[0, 2], [4, 6]]
      

      【讨论】:

      • 这太棒了 - 很好的答案,而且速度如此之快!唯一困扰我的是地图开头的数组,必须手动设置它以匹配捕获组的数量。也许这样的事情会解决这个问题? 1.upto(m.size-1).to_a.map{|i| [m.begin(i), m.end(i) - 1]}
      • 你可以这样做,但你不需要to_a
      猜你喜欢
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 2015-06-07
      • 2017-08-16
      相关资源
      最近更新 更多