Convert named matches in MatchData to Hash

后端 未结 5 1490
抹茶落季
抹茶落季 2021-02-12 13:45

I have a rather simple regexp, but I wanted to use named regular expressions to make it cleaner and then iterate over results.

Testing string:

testing_s         


        
5条回答
  •  死守一世寂寞
    2021-02-12 14:15

    @Phrogz's answer is correct if all of your captures have unique names, but you're allowed to give multiple captures the same name. Here's an example from the Regexp documentation.

    This code supports captures with duplicate names:

    captures = Hash[
      dimensions.regexp.named_captures.map do |name, indexes|
        [
          name,
          indexes.map { |i| dimensions.captures[i - 1] }
        ]
      end
    ]
    
    # Iterate over the captures
    captures.each do |name, values|
      # name is a String
      # values is an Array of Strings
    end
    

提交回复
热议问题