Rubular(Example)如何获得匹配组?
/regex(?<named> .*)/.match('some long string')
match方法(在示例中)仅返回第一个匹配。
scan方法返回没有命名捕获的数组。
获取一系列命名捕获(没有拆分)的最佳方法是什么?
答案 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 { $~ }