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/
/e/
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!
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]