ruby regex:匹配并获取位置

编程入门 行业动态 更新时间:2024-10-16 22:19:12
本文介绍了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:匹配并获取位置

本文发布于:2023-10-08 01:19:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471091.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位置   ruby   regex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!