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
You want all possible matches, including overlapping ones. As you've noted, the lookahead trick from "How to find overlapping matches with a regexp?" doesn't work for your case.
The only thing I can think of that will work in the general case is to generate all of the possible substrings of the string and check each one against an anchored version of the regex. This is brute-force, but it works.
Ruby:
def all_matches(str, regex)
(n = str.length).times.reduce([]) do |subs, i|
subs += [*i..n].map { |j| str[i,j-i] }
end.uniq.grep /^#{regex}$/
end
all_matches("abcadc", /a.*c/)
#=> ["abc", "abcadc", "adc"]
Javascript:
function allMatches(str, regex) {
var i, j, len = str.length, subs={};
var anchored = new RegExp('^' + regex.source + '$');
for (i=0; i