I\'m looking for a way, either in Ruby or Javascript, that will give me all matches, possibly overlapping, within a string against a regexp.
Let\'s say I have
Here's an approach that is similar to @ndn's and @Mark's that works with any string and regex. I've implemented this as a method of String
because that's where I'd like to see it. Wouldn't it be a great compliment to String#[]
and String#scan
?
class String
def all_matches(regex)
return [] if empty?
r = /^#{regex}$/
1.upto(size).with_object([]) { |i,a|
a.concat(each_char.each_cons(i).map(&:join).select { |s| s =~ r }) }
end
end
'abcadc'.all_matches /a.*c/
# => ["abc", "abcadc", "adc"]
'aaabaaa'.all_matches(/a.*a/)
#=> ["aa", "aa", "aa", "aa", "aaa", "aba", "aaa", "aaba", "abaa", "aaaba",
# "aabaa", "abaaa", "aaabaa", "aabaaa", "aaabaaa"]