我需要MatchData
对于字符串中正则表达式的每次出现。这与中建议的扫描方法不同匹配正则表达式的所有出现,因为这只给了我一个字符串数组(我需要完整的 MatchData,以获取开始和结束信息等)。
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)
我怀疑有一些我忽略的方法。建议?
你要
"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }
这给了你
[#<MatchData "12">, #<MatchData "34">, #<MatchData "567">]
正如您所看到的,“技巧”是构建一个枚举器以获得每个last_match
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)