Regex with named capture groups getting all matches in Ruby

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

    @Nakilon is correct showing scan with a regex, however you don't even need to venture into regex land if you don't want to:

    s = "123--abc,123--abc,123--abc"
    s.split(',')
    #=> ["123--abc", "123--abc", "123--abc"]
    
    s.split(',').inject([]) { |a,s| a << s.split('--'); a }
    #=> [["123", "abc"], ["123", "abc"], ["123", "abc"]]
    

    This returns an array of arrays, which is convenient if you have multiple occurrences and need to see/process them all.

    s.split(',').inject({}) { |h,s| n,v = s.split('--'); h[n] = v; h }
    #=> {"123"=>"abc"}
    

    This returns a hash, which, because the elements have the same key, has only the unique key value. This is good when you have a bunch of duplicate keys but want the unique ones. Its downside occurs if you need the unique values associated with the keys, but that appears to be a different question.

提交回复
热议问题