带有命名捕获组的正则表达式在 Ruby 中获取所有匹配项 [英] Regex with named capture groups getting all matches in Ruby

查看:30
本文介绍了带有命名捕获组的正则表达式在 Ruby 中获取所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

s="123--abc,123--abc,123--abc"

我尝试使用 Ruby 1.9 的新功能命名组"来获取所有命名组信息:

I tried using Ruby 1.9's new feature "named groups" to fetch all named group info:

/(?<number>\d*)--(?<chars>\s*)/

是否有像 Python 的 findall 这样返回 matchdata 集合的 API?在这种情况下,我需要返回两个匹配项,因为 123abc 重复两次.每个匹配数据都包含每个命名捕获信息的详细信息,因此我可以使用 m['number'] 来获取匹配值.

Is there an API like Python's findall which returns a matchdata collection? In this case I need to return two matches, because 123 and abc repeat twice. Each match data contains of detail of each named capture info so I can use m['number'] to get the match value.

推荐答案

命名捕获仅适用于一个匹配结果.
Ruby 的 findall 类似物是 String#scan.您可以使用 scan 结果作为数组,也可以将块传递给它:

Named captures are suitable only for one matching result.
Ruby's analogue of findall is String#scan. You can either use scan result as an array, or pass a block to it:

irb> s = "123--abc,123--abc,123--abc"
=> "123--abc,123--abc,123--abc"

irb> s.scan(/(\d*)--([a-z]*)/)
=> [["123", "abc"], ["123", "abc"], ["123", "abc"]]

irb> s.scan(/(\d*)--([a-z]*)/) do |number, chars|
irb*     p [number,chars]
irb> end
["123", "abc"]
["123", "abc"]
["123", "abc"]
=> "123--abc,123--abc,123--abc"

这篇关于带有命名捕获组的正则表达式在 Ruby 中获取所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆