【发布时间】:2016-11-24 09:21:24
【问题描述】:
Rubular (Example) 如何获取匹配组?
/regex(?<named> .*)/.match('some long string')
match 方法(示例)只返回第一个匹配项。
scan 方法返回一个没有命名捕获的数组。
获取命名捕获数组的最佳方法是什么(不拆分)?
【问题讨论】:
标签: ruby regex rubular named-captures
Rubular (Example) 如何获取匹配组?
/regex(?<named> .*)/.match('some long string')
match 方法(示例)只返回第一个匹配项。
scan 方法返回一个没有命名捕获的数组。
获取命名捕获数组的最佳方法是什么(不拆分)?
【问题讨论】:
标签: ruby regex rubular named-captures
我一直认为 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 { $~ }
【讨论】: