How to get possibly overlapping matches in a string

后端 未结 8 2138
别那么骄傲
别那么骄傲 2020-12-03 17:13

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

8条回答
  •  离开以前
    2020-12-03 17:43

    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

提交回复
热议问题