How do I get the match data for all occurrences of a Ruby regular expression in a string?

后端 未结 5 1298
难免孤独
难免孤独 2020-11-27 15:16

I need the MatchData for each occurrence of a regular expression in a string. This is different than the scan method suggested in Match All Occurrences of a Reg

5条回答
  •  半阙折子戏
    2020-11-27 15:38

    input = "abc12def34ghijklmno567pqrs"
    n = Regexp.new("\\d+")
    [n.match(input)].tap { |a| a << n.match(input,a.last().end(0)+1) until a.last().nil? }[0..-2]
    
    => [#, #, #]
    

提交回复
热议问题