How to get possibly overlapping matches in a string

后端 未结 8 2166
别那么骄傲
别那么骄傲 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:53

    def matching_substrings(string, regex)
      string.size.times.each_with_object([]) do |start_index, maching_substrings|
        start_index.upto(string.size.pred) do |end_index|
          substring = string[start_index..end_index]
          maching_substrings.push(substring) if substring =~ /^#{regex}$/
        end
      end
    end
    
    matching_substrings('abcadc', /a.*c/) # => ["abc", "abcadc", "adc"]
    matching_substrings('foobarfoo', /(\w+).*\1/) 
      # => ["foobarf",
      #     "foobarfo",
      #     "foobarfoo",
      #     "oo",
      #     "oobarfo",
      #     "oobarfoo",
      #     "obarfo",
      #     "obarfoo",
      #     "oo"]
    matching_substrings('why is this downvoted?', /why.*/)
      # => ["why",
      #     "why ",
      #     "why i",
      #     "why is",
      #     "why is ",
      #     "why is t",
      #     "why is th",
      #     "why is thi",
      #     "why is this",
      #     "why is this ",
      #     "why is this d",
      #     "why is this do",
      #     "why is this dow",
      #     "why is this down",
      #     "why is this downv",
      #     "why is this downvo",
      #     "why is this downvot",
      #     "why is this downvote",
      #     "why is this downvoted",
      #     "why is this downvoted?"]
    

提交回复
热议问题