ruby对于正则表达式的使用是非常灵活的,提供了专门的正则表达式对象Regexp.其包括match实例方法,字符串也含有该方法.so可以这么做:
/a/ =~ "a" "a" =~ /a/ "a".match("a") /a/.match("a")
但是在新版的ruby中不可以这样:
"a" =~ "a" #error!
另外正则的比较还可以用操作符===,其返回true/false表示是否匹配,但是对调一下结果就不一样,这点要注意:
irb(main):079:0> "a"===/a/ => false irb(main):080:0> /a/==="a" => true
下面举一个例子:
irb(main):083:0> str => "vax12345tn19980202.!!!" irb(main):084:0> v = str.match(/a(.)(\d+)(\D{1,5})(\d+)([,.:]?)/) => #<MatchData "ax12345tn19980202." 1:"x" 2:"12345" 3:"tn" 4:"19980202" 5:"."> irb(main):085:0> v[0] => "ax12345tn19980202." irb(main):086:0> v[1] => "x" irb(main):087:0> v[3] => "tn" irb(main):088:0> v.begin 0 => 1 irb(main):089:0> v.begin 3 => 8 irb(main):090:0> v.end 3 => 10 irb(main):091:0> v.offset 3 => [8, 10] irb(main):092:0> v.post_match => "!!!" irb(main):093:0> v.pre_match => "v" irb(main):094:0> v.string => "vax12345tn19980202.!!!" irb(main):095:0> v[2] => "12345"
为了使用方便(类似于用过就丢代码),也有全局匹配的正则表达式对象$~,操作和上面类似:
irb(main):097:0> str.match(/a(.)(\d+)(\D{1,5})(\d+)([,.:]?)/) => #<MatchData "ax12345tn19980202." 1:"x" 2:"12345" 3:"tn" 4:"19980202" 5:"."> irb(main):098:0> $~ => #<MatchData "ax12345tn19980202." 1:"x" 2:"12345" 3:"tn" 4:"19980202" 5:"."> irb(main):099:0> $& => "ax12345tn19980202." irb(main):100:0> $` => "v" irb(main):101:0> $' => "!!!" irb(main):102:0> $+ => "." irb(main):103:0> $1 => "x" irb(main):104:0> $2 => "12345" irb(main):105:0> $3 => "tn"
对于字符串也含有一些正则的表达式的实例方法,比如sub,gsub,scan等等,其中在sub,gsub之类的方法中第二个参数可以使用置换变量来表示:\&和\0表示整个匹配的字符串,\1至\9是第n个括号内匹配的字符串,另外也可以用\`,\'和\+它们和$`,$'和$+相对应:
irb(main):117:0> s="abc12345xyz" => "abc12345xyz" irb(main):118:0> s.sub(/(\d+)/,'(\&)') => "abc(12345)xyz"