正则表达式 Regular Expressions
2008-03-13 20:05:29
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://fsjoy.blog.51cto.com/318484/65653 |
正则表达式的作用:用来匹配字符串 类型:Regexp的对象 a=/\s/ puts a.class创建正则表达式: 1.可以通过调用构造函数来创建正则表达式: a=Regexp.new('^\s*[a-z]') -> ^\s*[a-z] #用构造函数注意'pattern' b=^\s*[a-z] c=%r{^\s*[a-z]} ================
有了正则表达式对象,可以使用Regexp#match(string)或匹配操作符=~(肯定匹配)和!=(否定匹配)对字符串进行匹配 匹配操作符两边至少有一个操作数必须为正则表达式
例:
name="Fats Waller" name=~/a/ ->1 name=~/z/ ->nil /a/ =~name ->1 #匹配操作符返回匹配发生的字符位置 ========
$&得到与模式匹配的那部分字符串,$`得到匹配之前的那部分字符串,而$'得到匹配之后的那部分字符串。下面使用这些变量来编写show_regexp方法,说明具体的模式在何处发生匹配:
def show_regexp(a, re) if a=~re "#{$`}<<#{$&}>>#{$'}" else "no match" end end puts show_regexp('very interesting', /t/) puts show_regexp('Fats Waller',/a/) puts show_regexp('Fats Waller',/ll/) puts show_regexp('Fats Waller',/z/)结果:
very in<<t>>eresting F<<a>>ts Waller Fats Wa<<ll>>er no match 本文出自 “李骥平” 博客,请务必保留此出处http://fsjoy.blog.51cto.com/318484/65653 本文出自 51CTO.COM技术博客 |


a=/\s/
a=Regexp.new('^\s*[a-z]') -> ^\s*[a-z] #用构造函数注意'pattern'
fsjoy1983
博客统计信息
热门文章
最新评论
友情链接
