Get index of string scan results in ruby

前端 未结 4 1201
半阙折子戏
半阙折子戏 2020-12-10 03:13

I want to get the index as well as the results of a scan

\"abab\".scan(/a/)

I would like to have not only

=> [\"a\", \"a         


        
4条回答
  •  醉话见心
    2020-12-10 03:34

    Very similar to what @jim has said and works a bit better for longer strings:

    def matches str, pattern
        arr = []
        while (str && (m = str.match pattern))      
            offset = m.offset(0).first 
            arr << offset + (arr[-1] ? arr[-1] + 1 : 0)
            str = str[(offset + 1)..-1]
        end
        arr
    end
    

提交回复
热议问题