ruby regex:匹配并获取位置 [英] ruby regex: match and get position(s) of

查看:37
本文介绍了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:匹配并获取位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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