ruby1.9 regexp match named captures

原创文章,转载请注明来源并保留原文链接

ruby中的捕获型括号:

str = "this is test data"
str =~ /(da)(ta)/

p $~
# => #(MatchData "data" 1:"da" 2:"ta")
p $~.to_a
# => ["data", "da", "ta"]
p $1
# => "da"
p $2
# => "ta"

ruby1.9终于加入了命名捕获,用来取代$1,$2这种可读性很差的方式。

p RUBY_VERSION
#=> "1.9.2"

str = "this is test data"
/(?<d>da)(?<t>ta)/ =~ str

p d
#=> "da"
p t
#=> "ta"

#***注意顺序***
str =~ /(?<ddd>da)(ta)/

p ddd
#=> undefined local variable or method `ddd' for main:Object

Leave a Reply

Your email address will not be published. Required fields are marked *