本文介绍了ruby regex:匹配并获取位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想匹配一个正则表达式并获取匹配字符串中的位置
例如
"AustinTexasDallasTexas".match_with_posn/(Texas)/我希望 match_with_posn 返回如下内容:[6, 17] 其中 6 和 17 是单词 Texas 的两个实例的起始位置.>
有这样的吗?
解决方案使用 Ruby 1.8.6+,您可以这样做:
require 'enumerator' #仅适用于 1.8.6,新版本不需要这个.s = "AustinTexasDallasTexas"位置 = s.enum_for(:scan,/Texas/).map { Regexp.last_match.begin(0) }这将创建一个数组:
=>[6, 17]I'd like to match a regex and get the position in the string of the match
For example,
"AustinTexasDallasTexas".match_with_posn /(Texas)/I'd like match_with_posn to return something like: [6, 17] where 6 and 17 are the start positions for both instances of the word Texas.
Is there anything like this?
解决方案Using Ruby 1.8.6+, you can do this:
require 'enumerator' #Only for 1.8.6, newer versions should not need this. s = "AustinTexasDallasTexas" positions = s.enum_for(:scan, /Texas/).map { Regexp.last_match.begin(0) }This will create an array with:
=> [6, 17]
更多推荐
ruby regex:匹配并获取位置
发布评论