ruby regex: match and get position(s) of

你。 提交于 2019-11-27 01:33:29

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]

Sort of, see String#index

"AustinTexasDallasTexas".index /Texas/
=> 6

Now, you could extend the String 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]
"AustinTexasDallasTexas".gsub(/Texas/).map { Regexp.last_match.begin(0) }
  #=> [6, 17]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!