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

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

    I’ll put it here to make the code available via a search:

    input = "abc12def34ghijklmno567pqrs"
    numbers = /\d+/
    input.gsub(numbers) { |m| p $~ }
    

    The result is as requested:

    ⇒ #
    ⇒ #
    ⇒ #
    

    See "input.gsub(numbers) { |m| p $~ } Matching data in Ruby for all occurrences in a string" for more information.

提交回复
热议问题