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代码

  1. users = %w{
  2. alice:10.23.52.112:true
  3. bob:192.168.10.34:false
  4. }
  5. user_regexp = %r{
  6. (?<username> [a-z]+ ){0}
  7. (?<ip_number> [0-9]{1,3} ){0}
  8. (?<ip_address> (\g<ip_number>\.){3}\g<ip_number> ){0}
  9. (?<admin> true | false ){0}
  10. \g<username>:\g<ip_address>:\g<admin>
  11. }x
  12. users.each do |u|
  13. r = user_regexp.match(u)
  14. puts "User #{r[:username]} is from #{r[:ip_address]}"
  15. end

使用match和hash的方式,以组的命名作为key就可以访问匹配内容了。

ruby正则教程

http://www.regular-expressions.info/ruby.html

http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm#_Regular_Expressions