如何在ruby中匹配组,如Rubular而不拆分字符串

时间:2016-07-21 00:50:19

标签: ruby regex rubular named-captures

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

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

match方法(在示例中)仅返回第一个匹配。

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

获取一系列命名捕获(没有拆分)的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

我一直认为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 { $~ }