Regex with named capture groups getting all matches in Ruby

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

    Piggybacking off of Mark Hubbart's answer, I added the following monkey-patch:

    class ::Regexp
      def match_all(str)
        matches = []
        str.scan(self) { matches << $~ }
    
        matches
      end
    end
    

    which can be used as /(?\w)/.match_all('word'), and returns:

    [#, #, #, #]

    This relies on, as others have said, the use of $~ in the scan block for the match data.

提交回复
热议问题