gpt4 book ai didi

ruby 正则表达式 : match and get position(s) of

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:45 25 4
gpt4 key购买 nike

我想匹配一个正则表达式并获取匹配字符串中的位置

例如,

"AustinTexasDallasTexas".match_with_posn /(Texas)/

我想要match_with_posn返回类似:[6, 17]其中 6 和 17 是单词 Texas 的两个实例的起始位置。

有这样的吗?

最佳答案

使用 Ruby 1.8.6+,你可以这样做:

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) }

这将创建一个数组:

=> [6, 17]

关于 ruby 正则表达式 : match and get position(s) of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5241653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com