Ruby 1.9 regex (named capture group)正则名组
regexp = /a/
result = subject.scan(regexp)
ruby-1.9.2-p0 > result = subject.scan(regexp)
NameError: undefined local variable or method `subject' for main:Object
from (irb):8
from /home/mlzboy/.rvm/rubies/ruby-1.9.2-p0/bin/irb:16:in `<main>'
ruby-1.9.2-p0 > subject="abcabc"
=> "abcabc"
ruby-1.9.2-p0 > result = subject.scan(regexp)
=> ["a", "a"]
ruby-1.9.2-p0 > ^C
ruby-1.9.2-p0 >
2011 - 01 - 08
Ruby 1.9 regex (named capture group) 文章分类: Ruby编程
Ruby 1.9正则增加了支持命名组,这样使得正则具有更好的可读行,
你可以定义每一部分的正则,然后命名成组,并且在后面加上
{0},表明不获取匹配内容,然后在使用\g引用对用的组,组成
大的正则,并且加上/x修饰。这样比较复杂的正则,会有更好的可读性。
Ruby代码
users = %w{ alice:10.23.52.112 :true bob:192.168.10.34 :false } user_regexp = %r{ (?<username> [a-z]+ ){0} (?<ip_number> [0-9]{1,3} ){0} (?<ip_address> (\g<ip_number>\.){3}\g<ip_number> ){0} (?<admin> true | false ){0} \g<username>:\g<ip_address>:\g<admin> }x users. each do |u| r = user_regexp.match(u) puts "User #{r[:username]} is from #{r[:ip_address]}" end
使用match和hash的方式,以组的命名作为key就可以访问匹配内容了。
ruby正则教程
http://HdhCmsTestregular-expressions.info/ruby.html
http://HdhCmsTesttroubleshooters测试数据/codecorn/ruby/basictutorial.htm#_Regular_Expressions
查看更多关于Ruby 1.9 regex (named capture group)正则名组的详细内容...