Regex with named capture groups getting all matches in Ruby

前端 未结 10 1977
滥情空心
滥情空心 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:01

    I really liked @Umut-Utkan's solution, but it didn't quite do what I wanted so I rewrote it a bit (note, the below might not be beautiful code, but it seems to work)

    class String
      def scan2(regexp)
        names = regexp.names
        captures = Hash.new
        scan(regexp).collect do |match|
          nzip = names.zip(match)
          nzip.each do |m|
            captgrp = m[0].to_sym
            captures.add(captgrp, m[1])
          end
        end
        return captures
      end
    end
    

    Now, if you do

    p '12f3g4g5h5h6j7j7j'.scan2(/(?[a-zA-Z])(?[0-9])/)
    

    You get

    {:alpha=>["f", "g", "g", "h", "h", "j", "j"], :digit=>["3", "4", "5", "5", "6", "7", "7"]}
    

    (ie. all the alpha characters found in one array, and all the digits found in another array). Depending on your purpose for scanning, this might be useful. Anyway, I love seeing examples of how easy it is to rewrite or extend core Ruby functionality with just a few lines!

提交回复
热议问题