gpt4 book ai didi

ruby - 如何在不拆分字符串的情况下像 Rubular 一样在 ruby​​ 中获取匹配组

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:53 25 4
gpt4 key购买 nike

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

/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 { $~ }

关于ruby - 如何在不拆分字符串的情况下像 Rubular 一样在 ruby​​ 中获取匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com