Ruby Regex, get all possible matches (no clipping of the string)
regex, ruby
Solution
Kind of old topic... Not sure if I understand, but best I can find is this:
"Hey".scan(/(?=(..))/)
=> [["He"], ["ey"]]
"aaaaaa".scan(/(?=(..+)\1)/)
=> [["aaa"], ["aa"], ["aa"]]
scan walks thru every byte and the "positive look-ahead" `(?=)` tests the regexp `(..+)\1` in every step. Look-aheads don't consume bytes, but the capture group inside it returns the match if it exists.
Problem
I have run into a problem with the ruby regex. I need to find all (potentially overlapping) matches. This is a simplification of the problem: ``` #Simple example "Hey".scan(/../) => ["He"] #Actual results #With overlapping matches the result should be => ["He"], ["ey"] ``` The regex I am trying to execute and get all results for looks like this: ``` "aaaaaa".scan(/^(..+)\1+$/) #This looks for multiples of (here) "a" bigger than one that "fills" the entire string. "aa"*3 => true, "aaa"*2 => true. "aaaa"*1,5 => false. => [["aaa"]] #With overlapping results this should be => [["aa"],["aaa"]] ``` Is there a library or a way to do regex in ruby to get the results I am after? I found some clues that this was possible in Perl, but after hours of research I did not find anything about a Ruby way of doing this. However I was able to find this "Javascript Regex - Find all possible matches, even in already captured matches", but I am not able to find anything similar for Ruby, nor find something similar to the last index property in the Ruby version. To be honest I don't think that it would have worked anyways since the regex I intend to use is recursive and relies on the entire string, while that method chops away at the string.