How to get possibly overlapping matches in a string

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

    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"] 
    

提交回复
热议问题