Regex with named capture groups getting all matches in Ruby

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

    If using ruby >=1.9 and the named captures, you could:

    class String 
      def scan2(regexp2_str, placeholders = {})
        return regexp2_str.to_re(placeholders).match(self)
      end
    
      def to_re(placeholders = {})
        re2 = self.dup
        separator = placeholders.delete(:SEPARATOR) || '' #Returns and removes separator if :SEPARATOR is set.
        #Search for the pattern placeholders and replace them with the regex
        placeholders.each do |placeholder, regex|
          re2.sub!(separator + placeholder.to_s + separator, "(?<#{placeholder}>#{regex})")
        end    
        return Regexp.new(re2, Regexp::MULTILINE)    #Returns regex using named captures.
      end
    end
    

    Usage (ruby >=1.9):

    > "1234:Kalle".scan2("num4:name", num4:'\d{4}', name:'\w+')
    => #
    

    or

    > re="num4:name".to_re(num4:'\d{4}', name:'\w+')
    => /(?\d{4}):(?\w+)/m
    
    > m=re.match("1234:Kalle")
    => #
    > m[:num4]
    => "1234"
    > m[:name]
    => "Kalle"
    

    Using the separator option:

    > "1234:Kalle".scan2("#num4#:#name#", SEPARATOR:'#', num4:'\d{4}', name:'\w+')
    => #
    

提交回复
热议问题