如何在 ruby​​ 中进行命名捕获 [英] How to do named capture in ruby

查看:30
本文介绍了如何在 ruby​​ 中进行命名捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想命名我从扫描中获得的字符串捕获.怎么做?

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", "7777"]

有没有可能变成这样

{:area => "555", :city => "333", :local => "7777" }

[["555","area"], [...]]

我试过了

"555-333-7777".scan(/((?<area>)\d{3})-(\d{3})-(\d{4})/).flatten

但它返回

[]

推荐答案

您应该将 match 用于命名捕获,而不是 scan

You should use match with named captures, not scan

m = "555-333-7777".match(/(?<area>\d{3})-(?<city>\d{3})-(?<number>\d{4})/)
m # => #<MatchData "555-333-7777" area:"555" city:"333" number:"7777">
m[:area] # => "555"
m[:city] # => "333"

如果你想要一个实际的哈希,你可以使用这样的东西:

If you want an actual hash, you can use something like this:

m.names.zip(m.captures).to_h # => {"area"=>"555", "city"=>"333", "number"=>"7777"}

或者这个(ruby 2.4 或更高版本)

Or this (ruby 2.4 or later)

m.named_captures # => {"area"=>"555", "city"=>"333", "number"=>"7777"}

这篇关于如何在 ruby​​ 中进行命名捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆