正则表达式很多用来处理可选项和重复
例1:例子中?匹配0个或一个x
pattern= /ax?b/
puts pattern=~ "ab" #0
puts pattern=~ "axb" #0
puts pattern=~ "axxb" #nil
puts pattern=~ "acb" #nil
puts pattern=~ "ab" #0
puts pattern=~ "axb" #0
puts pattern=~ "axxb" #nil
puts pattern=~ "acb" #nil
例2:
pattern= /a[xy]?b/
puts pattern=~ "ab" #0
puts pattern=~ "axb" #0
puts pattern=~ "ayb" #0
puts pattern=~ "axyb" #nil
puts pattern=~ "ab" #0
puts pattern=~ "axb" #0
puts pattern=~ "ayb" #0
puts pattern=~ "axyb" #nil
[str]代表匹配其中一个字符,[str]?代表str中的其中一个字符有0个或1个
*代表0个或多个,+代表1个或多个
---匹配美国社会保险号的例子:
ssn=
"987-65-4320"
pattern =/\d\d\d-\d\d-\d\d\d\d/
puts pattern=~ssn #0
pattern =/\d\d\d-\d\d-\d\d\d\d/
puts 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{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,}/
/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]
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]
match=/.*?the/.match(str)
p match[0]
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/68435,如需转载请自行联系原作者