ruby正则表达式:匹配并获取
我想匹配一个正则表达式并获得匹配字符串中的位置 比如说,ruby正则表达式:匹配并获取,ruby,regex,Ruby,Regex,我想匹配一个正则表达式并获得匹配字符串中的位置 比如说, "AustinTexasDallasTexas".match_with_posn /(Texas)/ 我希望将\u与\u posn匹配返回如下内容:[6,17],其中6和17是单词Texas的两个实例的起始位置 有类似的吗?有点像,请参见 现在,您可以扩展字符串API class String def indices e start, result = -1, [] result << start whi
"AustinTexasDallasTexas".match_with_posn /(Texas)/
我希望将\u与\u posn匹配
返回如下内容:[6,17]
,其中6和17是单词Texas的两个实例的起始位置
有类似的吗?有点像,请参见
现在,您可以扩展字符串API
class String
def indices e
start, result = -1, []
result << start while start = (self.index e, start + 1)
result
end
end
p "AustinTexasDallasTexas".indices /Texas/
=> [6, 17]
类字符串
def指数e
开始,结果=-1,[]
结果[6,17]
使用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]
如果您想在IsateateTest中找到atea,它将返回[2],但5也是一种可能性。索引5中的“a”用于匹配在索引2中找到的“atea”。如果搜索“ate”,您将得到一个
[2,5,8]
数组。如果要查找重叠的匹配项,请使用先行断言:/(?=(atea))/
positions=s.enum_for(:scan,/(?=(atea))/).map{Regexp.last_match.begin(0)}#=>[2,5]
否决此投票的人可以解释否决票吗?你能详细解释一下吗。它返回了scan
的枚举数,它在一个字符串中查找传递给它的参数的匹配项,在这种情况下,/Texas/
。如果没有枚举数,它通常会返回字符串中匹配的部分。因为我们使用的是枚举器,所以我们可以映射匹配项,这样我们就可以为每个扫描
结果返回索引。本质上发生的是,map
调用中的每个步骤调用enum\u为
返回的枚举器上的next
,然后返回块内的值。假设字符串为“aaaa”
和e
为“aa”
,则可能重复。问题不清楚所需的返回值是[0,1,2]
还是[0,2]
。你返回前者。要返回后者,请生成索引
的第二个参数start+e.size
,并将start
初始化为-e.size
。无需使用self.
。
=> [6, 17]
"AustinTexasDallasTexas".gsub(/Texas/).map { Regexp.last_match.begin(0) }
#=> [6, 17]