Regex with named capture groups getting all matches in Ruby

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

    I needed something similar recently. This should work like String#scan, but return an array of MatchData objects instead.

    class String
      # This method will return an array of MatchData's rather than the
      # array of strings returned by the vanilla `scan`.
      def match_all(regex)
        match_str = self
        match_datas = []
        while match_str.length > 0 do 
          md = match_str.match(regex)
          break unless md
          match_datas << md
          match_str = md.post_match
        end
        return match_datas
      end
    end
    

    Running your sample data in the REPL results in the following:

    > "123--abc,123--abc,123--abc".match_all(/(?\d*)--(?[a-z]*)/)
    => [#,
        #,
        #]
    

    You may also find my test code useful:

    describe String do
      describe :match_all do
        it "it works like scan, but uses MatchData objects instead of arrays and strings" do
          mds = "ABC-123, DEF-456, GHI-098".match_all(/(?[A-Z]+)-(?[0-9]+)/)
          mds[0][:word].should   == "ABC"
          mds[0][:number].should == "123"
          mds[1][:word].should   == "DEF"
          mds[1][:number].should == "456"
          mds[2][:word].should   == "GHI"
          mds[2][:number].should == "098"
        end
      end
    end
    

提交回复
热议问题