ruby的正则表达式操作(2)

作者: 孤独的猫
发布时间:2015-07-13 11:31:57

ruby的正则表达式中的字符类缩写

字符      是         含义

\d                [0-9]                   数字字符

\D                [^0-9]                     除数字之外的任何字符

\s                 [ \t\r\n\f]                 空格字符

\S                [^ \t\r\n\f]               除空格之外的任何字符

\w                 [A-Za-z0-9]            组词字符

\W               [^A-Za-z0-9]            除组词字符之外的任何字符

 

测试如下

irb(main):001:0> a="the quick brown fox"
=> "the quick brown fox"
irb(main):002:0> a.sub(/[aeiou]/,'*')
=> "th* quick brown fox"
irb(main):003:0> a.gsub(/[aeiou]/,'*')
=> "th* q**ck br*wn f*x"
irb(main):004:0> a.sub(/\s\S+/,'*')
=> "the* brown fox"
irb(main):005:0> a.gsub(/\s\S+/,'*')
=> "the***"
irb(main):006:0> a.sub(/\s\S+/,'')
=> "the brown fox"
irb(main):007:0> a.gsub(/\s\S+/,'')
=> "the"
irb(main):008:0>

来源:http://www.cnblogs.com/djcsch2001/archive/2012/03/23/2414228

推荐: