ruby 正则表达式 使用量词符

简介:
正则表达式很多用来处理可选项和重复
例1:例子中?匹配0个或一个x
InBlock.gifpattern= /ax?b/ 
InBlock.gifputs pattern=~ "ab"     #0 
InBlock.gifputs pattern=~ "axb"    #0 
InBlock.gifputs pattern=~ "axxb"   #nil 
InBlock.gifputs pattern=~ "acb"    #nil
例2:
InBlock.gifpattern= /a[xy]?b/     
InBlock.gifputs pattern=~ "ab"      #0
InBlock.gifputs pattern=~ "axb"     #0
InBlock.gifputs pattern=~ "ayb"     #0
InBlock.gifputs pattern=~ "axyb"    #nil
[str]代表匹配其中一个字符,[str]?代表str中的其中一个字符有0个或1个
*代表0个或多个,+代表1个或多个
---匹配美国社会保险号的例子:
InBlock.gifssn= "987-65-4320" 
InBlock.gifpattern =/\d\d\d-\d\d-\d\d\d\d/ 
InBlock.gifputs pattern=~ssn              #0
这里的pattern可以写成 pattern=/\d{3}-\d{2}-\d{4}/
例3:
假设一个国家的电话号码由两部分组成:(第一部分3~5个数字)-(第二部分3~7个数字)
模式:pattern=/\d{3,5}-\d{3,7}/
开头与末尾的数字可选,但必须有其中的一个:
/x{5}/    #match 5 xs 
/x{5,7}/  #match 5-7 xs 
/x{,8}/   #match up to 8 xs 
/x{3,}/   #match at least 3 xs
所以量词符 ?,+和*可以这样重写:
/x?/ #same as /x{0,1}/ 
/x+/ #same as /x{1,}/ 
/x*/ #same as /x{0,}/
贪婪的“*”( greedy)
例:
str="where the sea meets the moon-blanch'd land," 
match=/.*the/.match(str) 
p match[0]
"where the sea meets the"
*是贪婪的,它匹配尽可能长的字符串,可以在它后面加上问号使其变为非贪婪的:
str="where the sea meets the moon-blanch'd land," 
match=/.*?the/.match(str) 
p match[0]
"where the"




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/68435,如需转载请自行联系原作者
目录
相关文章
|
3月前
|
Ruby
|
1月前
|
机器学习/深度学习 Java 索引
39、一篇文章弄懂 Java 正则表达式中的量词、贪婪、勉强、独占和 String 的 matches 方法的底层【个人感觉非常值得学习】
39、一篇文章弄懂 Java 正则表达式中的量词、贪婪、勉强、独占和 String 的 matches 方法的底层【个人感觉非常值得学习】
30 0
|
3月前
|
Ruby
|
3月前
|
Ruby
|
9月前
|
vr&ar
正则表达式中的量词
正则表达式中的量词
49 0
|
JavaScript
js基础笔记学习202正则表达式语法3量词
js基础笔记学习202正则表达式语法3量词
56 0
js基础笔记学习202正则表达式语法3量词
|
Ruby 索引
【Ruby on Rails全栈课程】2.5 正则表达式
1、正则表达式(Regexp) 正则表达式是对字符串操作的公式,用来过滤字符串或者从字符串中匹配出我们需要的字符,在各类语言中都有应用
96 0
【Ruby on Rails全栈课程】2.5 正则表达式
全网最易懂的正则表达式教程(3)- 量词
全网最易懂的正则表达式教程(3)- 量词
96 0
Rubular: 基于 Web 的 Ruby 正则表达式编辑器
当我们在 Ruby 项目中使用正则表达式时,如果想要即刻看到该正则的匹配结果,似乎除了跑代码外别无他法。假如匹配有误,我们必须回头重新修订正则表达式。如此周而复始,不仅效率低下,而且费时不少。如果我们利用Rubular 这个基于 Web 的 Ruby正则表达式编辑器,则问题迎刃而解。
398 0
Rubular: 基于 Web 的 Ruby 正则表达式编辑器
ruby的正则表达式操作(1)
ruby语言中用~/字符/来匹配表达式,$`得到匹配之前的那部分字符串,$'得到匹配之后的字符串,$&得到匹配到的字符串,如下所示 def show_regexp(a,re)    if a=~re        puts "#{$`}#{$'}"    else        puts "no ...
682 0

热门文章

最新文章