如何获取字符串中所有出现的 Ruby 正则表达式的匹配数据? [英] How do I get the match data for all occurrences of a Ruby regular expression in a string?

查看:54
本文介绍了如何获取字符串中所有出现的 Ruby 正则表达式的匹配数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于字符串中每次出现的正则表达式,我都需要 MatchData.这与 匹配正则表达式的所有出现,因为那只给了我一个字符串数组(我需要完整的 MatchData,以获取开始和结束信息等).

I need the MatchData for each occurrence of a regular expression in a string. This is different than the scan method suggested in Match All Occurrences of a Regex, since that only gives me an array of strings (I need the full MatchData, to get begin and end information, etc).

input = "abc12def34ghijklmno567pqrs"
numbers = /\d+/

numbers.match input # #<MatchData "12"> (only the first match)
input.scan numbers  # ["12", "34", "567"] (all matches, but only the strings)

我怀疑有些方法我忽略了.建议?

I suspect there is some method that I've overlooked. Suggestions?

推荐答案

你想要

"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }

给你

[#<MatchData "12">, #<MatchData "34">, #<MatchData "567">] 

如您所见,技巧"是构建一个枚举器以获取每个 last_match.

The "trick" is, as you see, to build an enumerator in order to get each last_match.

这篇关于如何获取字符串中所有出现的 Ruby 正则表达式的匹配数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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