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

后端 未结 5 1294
难免孤独
难免孤独 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:32

    I'm surprised nobody mentioned the amazing StringScanner class included in Ruby's standard library:

    require 'strscan'
    
    s = StringScanner.new('abc12def34ghijklmno567pqrs')
    
    while s.skip_until(/\d+/)
      num, offset = s.matched.to_i, [s.pos - s.matched_size, s.pos - 1]
    
      # ..
    end
    

    No, it doesn't give you the MatchData objects, but it does give you an index-based interface into the string.

提交回复
热议问题