How to do named capture in ruby

前端 未结 3 1269
無奈伤痛
無奈伤痛 2021-02-04 23:28

I want to name the capture of string that I get from scan. How to do it?

\"555-333-7777\".scan(/(\\d{3})-(\\d{3})-(\\d{4})/).flatten #=> [\"555\", \"333\", \"         


        
3条回答
  •  臣服心动
    2021-02-05 00:32

    A way to turn capture group names and their values into a hash is to use a regex with named captures using (? and then access the %~ global "last match" variable.

    regex_with_named_capture_groups = %r'(?\d{3})-(?\d{3})-(?\d{4})'
    "555-333-7777"[regex_with_named_capture_groups]
    
    match_hash = $~.names.inject({}){|mem, capture| mem[capture] = $~[capture]; mem}
    # => {"area"=>"555", "city"=>"333", "local"=>"7777"}
    
    # If ActiveSupport is available
    match_hash.symbolize_keys!
    # => {area: "555", city: "333", local: "7777"}
    

提交回复
热议问题