How to get indexes of all occurrences of a pattern in a string

前端 未结 2 429
梦如初夏
梦如初夏 2020-12-14 11:41
string = \"Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. \"
d = string.match(/(jack|jill         


        
2条回答
  •  时光说笑
    2020-12-14 12:04

    Here's a modification of Nakilon's answer if you want to put just the locations of "Jack" into an array

    location_array = Array.new
    
    string = "Jack and Jack went up the hill to fetch a pail of Jack..."  
    string.to_enum(:scan,/(jack)/i).map do |m,|
        location_array.push [$`.size]
    end
    

提交回复
热议问题