码迷,mamicode.com
首页 > 其他好文 > 详细

ruby 正则表达式

时间:2016-11-19 16:08:08      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:情况   不能   mat   删除   not   method   匹配   实用   没有   

Ruby学习笔记-正则表达式

Posted on 2011-11-29 17:55 Glen He 阅读(4998) 评论(0) 编辑 收藏
 
1.创建正则表达式
a)  reg1 = /^[a-z]*$/                             #将模式的定义放在两个正斜杠之间,返回一个Regexp对象
b)  reg2 = Regexp.new(‘^[a-z]*$’)         #创建一个Regexp对象
c)  reg3 = %r{^[a-z]*$}                       #使用前置的%r
 
2.匹配正则式: String和Regexp都支持以下两个方法
a) match方法: 匹配成功时返回MatchData类的一个实例;否则返回nil;
b) =~ 操作符: 匹配成功,返回一个索引(integer);否则,返回nil;
例:
       puts( /abc/ =~ abc )                 #=>return 0
       puts( /abc/ =~ cdg )                #=>return nil
       puts( /abc/.match(abc) )          #=>return abc
       puts( /abc/.match(cdg) )          #=>return nil
 
3.匹配组
在Ruby正则表达式中,可以用正则式匹配一个或多个子字符串;方法是将正
则式用小括号括起来;使用小括号指定的获取子字符串,可以将匹配的字符串保存;如下正则式中有两个组(hi)和(h…o):
  /(hi).*(h...o)/ =~ "The word ‘hi‘ is short for ‘hello‘."
匹配成功时, 会把匹配的值赋给一些变量(正则式中有多少组就有多少变量), 这些变量可以通过$1,$2,$3…的形式访问;如果执行上面的那行代码,可以使用$1,$2来访问变量:
       print ( $1, " ", $2, "\n" ) #=> hi hello
 
Note: 如果整个正则式匹配不成功,那么就不会就有变量被初始化, 而是返回nil.
  
4. MatchData类型
前面也提到过了,使用=~时返回的是一个整数或nil, 面使用match方法时会返回MatchData对象, 它包含了匹配模式的结果;乍一看,很像是字符串: 
   puts( /cde/.match(abcdefg) ) #=> cde           #=>cde
       puts( /cde/=~(abcdefg) ) #=> cde             #=>2
实际上, 它是MatchData类的一个实例且包含一个字符串:
       p( /cde/.match(abcdefg) )                         #=> #<MatchData: “cde” >
可以使用MatchData对象的to_a或captures方法返回包含其值的一个数组:
       x = /(^.*)(#)(.*)/.match( ‘def myMethod    # This is a very nice method‘ )
       x.captures.each{ |item| puts( item ) }
上面代码会输出:
       def myMethod
       #
       This is a very nice method
 
Note: captures 和to_a方法有一点点区别,后者会包含原始串
       x.captures     #=>["def myMethod ","#"," This is a very nice method"]
       x.to_a           #=>["def myMethod # This is a very nice method","def myMethod ","#"," This is a very nice method"]
 
5. Pre & Post 方法
a)  pre_match或($`): 返回匹配串前的串
b)  post_match或($): 返回匹配串后的串
  x = /#/.match( ‘def myMethod # This is a very nice method‘ )
  puts( x.pre_match )            #=> def myMethod
  puts( x.post_match )          #=> This is a very nice method
 
6. 贪婪匹配
当一个字符串包含多个可能的匹配时,有时可能只想返回第一个匹配的串;
有时可能想返回所有匹配的串,这种情况就叫贪婪匹配;符号*(0 or more) 和 + (1 or more)可以用来进行贪婪匹配。使用符号? (0 or 1) 进行最少匹配;
       puts( /.*at/.match(The cat sat on the mat!) )    #=> returns: The cat sat on the mat
   puts( /.*?at/.match(The cat sat on the mat!) )  #=> returns: The cat
 
7. 字符串中的方法
a)  =~ 和match: 用法同Regexp.
b)  String.scan(pattern):尽可能多的去匹配,并把第一个匹配添加到数组中.
  TESTSTR = "abc is not cba"
  b = /[abc]/.match( TESTSTR )           #=> MatchData: "a" puts( "--scan--" )
  a = TESTSTR.scan(/[abc]/)                   #=> Array: ["a", "b", "c", "c", "b", "a"]
此外,还可以给sacn方法传递一个block:
      a = TESTSTR.scan(/[abc]/){|c| print( c.upcase ) } #=> ABCCBA


“fjkdlasjfldjffjladsjflka;jd".scan(/(f)(j)k/){|t| puts "#{t}>>>>>>>>>>>>>"}
["f", "j"]>>>>>>>>>  
如果正则当中有括号,t代表的是由匹配到括号中的模式的值组成的数组,
如果没有括号,t代表匹配整个模式的值


 
c)  String.split(pattern):基于pattern来分割原串并返回一个数组;如果pattern为空(//),就把原串分割为字符;
  s = "def myMethod      # a comment"
  p( s.split( /m.*d/ ) )      # => ["def ", " # a comment"]
  p( s.split( /\s/ ) )           #=> ["def", "myMethod", "#", "a", "comment"]
  p( s.split( // ) )             # => ["d", "e", "f", " ", "m", "y", "M", "e", "t", "h", "o", "d", " ", "#", " ", "a", " ", "c", "o", "m", "m", "e", "n", "t"]
 
d) String. slice(pattern):返回匹配的串(原串不变),
    String. Slice!(pattern):返回匹配的串并在原串删除匹配的串(修改了原串的值)
  s = "def myMethod                 # a comment "
  puts( s.slice( /m.*d/ ) )          #=> myMethod
  puts( s )                                 #=> def myMethod # a comment
  puts( s.slice!( /m.*d/ ) )        #=> myMethod
  puts( s )                                    #=> def # a comment
 
8.正则表达式匹配规则
 
规则
说明
/a/
匹配字符a
/\?/
匹配特殊字符?。特殊字符包括^, $, ? , ., /, \, [, ], {, }, (, ), +, *.
.
匹配任意字符,例如/a./匹配ab和ac。   
/[ab]c/
匹配ac和bc,[]之间代表范围,例如:/[a-z]/ , /[a-zA-Z0-9]//[^a-zA-Z0-9]/
匹配不在该范围内的字符串
/[\d]/
代表任意数字
/[\w]/
代表任意字母,数字或者_
/[\s]/
代表空白字符,包括空格,TAB和换行
/[\D]/,/[\W]/,/[\S]/
均为上述的否定情况
?
代表0或1个字符
*
代表0或多个字符
+
代表1或多个字符
/d{3}/
匹配3个数字
/d{1,10}/
匹配1-10个数字
d{3,}/
匹配3个数字以上
/([A-Z]\d){5}/
匹配首位是大写字母,后面4个是数字的字符串
 
 . 匹配不到 \n        单独的一个反斜杠不能作为任何合法的字符   转义字符计算字符串长度时只能计作一个字符
字符串“abc\0xyz”:其中有一个转义字符\0,它是字符串结束符,所以,当用函数strlen来测试该字符串的长度时,结果应该为4(而不是8)。


str= "<p>一个反斜杠不能作为\n</p>"
str.scan(/<p>.*?\n<\/p>/)   返回[]   因为其中有\n  .无法匹配       只要字符串当中出现了\n  实用.去匹配就返回nil

 

ruby 正则表达式

标签:情况   不能   mat   删除   not   method   匹配   实用   没有   

原文地址:http://www.cnblogs.com/znsongshu/p/6080596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!