如何在不拆分字符串的情况下在类似ruby的Rubular中获得Match Groups



Rubular(示例)如何获取匹配组?

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

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

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

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

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

最新更新