Regex with named capture groups getting all matches in Ruby

前端 未结 10 1959
滥情空心
滥情空心 2021-02-02 08:12

I have a string:

s=\"123--abc,123--abc,123--abc\"

I tried using Ruby 1.9\'s new feature \"named groups\" to fetch all named group info:

10条回答
  •  野的像风
    2021-02-02 09:16

    You can extract the used variables from the regexp using names method. So what I did is, I used regular scan method to get the matches, then zipped names and every match to create a Hash.

    class String
      def scan2(regexp)
        names = regexp.names
        scan(regexp).collect do |match|
          Hash[names.zip(match)]
        end
      end
    end
    

    Usage:

    >> "aaa http://www.google.com.tr aaa https://www.yahoo.com.tr ffffd".scan2 /(?(?https?):\/\/[\S]+)/
    => [{"url"=>"http://www.google.com.tr", "protocol"=>"http"}, {"url"=>"https://www.yahoo.com.tr", "protocol"=>"https"}]
    

提交回复
热议问题