Return indices of all regex occurrences in a string in Ruby

How do I get an array of indices (or positions) of all occurrences of a regex in a string?

example_string= "hello how are you?

      

I would like to get array [1,12] for regexp /e/

+3


source to share


2 answers


Here's one approach for getting an array of match indices:

example_string = "hello how are you?"

example_string.enum_for(:scan, /e/).map { Regexp.last_match.begin(0) }

# => [1, 12]

      



Hope it helps!

+6


source


This is a great variation on @ Zoren's answer:



example_string = "hello how are you?"

example_string.gsub(/e/).with_object([]) { |_,a| a << Regexp.last_match.begin(0) }
 #=> [1, 12] 

      

+4


source







All Articles