【问题标题】:How to get Match Groups in ruby like Rubular without spliting the string如何在不拆分字符串的情况下获得像 Rubular 这样的红宝石匹配组
【发布时间】:2016-11-24 09:21:24
【问题描述】:

Rubular (Example) 如何获取匹配组?

/regex(?<named> .*)/.match('some long string')

match 方法(示例)只返回第一个匹配项。

scan 方法返回一个没有命名捕获的数组。

获取命名捕获数组的最佳方法是什么(不拆分)?

【问题讨论】:

    标签: ruby regex rubular named-captures


    【解决方案1】:

    我一直认为 Rubular 的工作原理是这样的:

    matches = []
    
    "foobar foobaz fooqux".scan(/foo(?<named>\w+)/) do
      matches << Regexp.last_match
    end
    
    p matches
    # => [ #<MatchData "foobar" named:"bar">,
    #      #<MatchData "foobaz" named:"baz">,
    #      #<MatchData "fooqux" named:"qux"> ]
    

    如果我们使用 enum_for$~Regexp.last_match 的别名),我们可以让它更 Rubyish:

    matches = "foobar foobaz fooqux".enum_for(:scan, /foo(?<named>\w+)/).map { $~ }
    

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2019-10-23
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多