[ACCEPTED]-ruby regex: match and get position(s) of-regex
Accepted answer
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 1 will create an array with:
=> [6, 17]
Sort of, see String#index
"AustinTexasDallasTexas".index /Texas/
=> 6
Now, you could extend the String 1 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]
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.