当前位置: 移动技术网 > IT编程>脚本编程>Ruby > 举例初步讲解Ruby中的正则表达式

举例初步讲解Ruby中的正则表达式

2017年12月08日  | 移动技术网IT编程  | 我要评论

 正则表达式是一个特殊的字符序列可以帮助匹配或者找到其他字符串或串套,使用的模式保持一个专门的语法。

正则表达式文本是一个模式之间的斜线之间或任意分隔符 %r 如下:
语法:

复制代码 代码如下:
/pattern/
/pattern/im    # option can be specified
%r!/usr/local! # general delimited regular expression

例如:

#!/usr/bin/ruby

line1 = "cats are smarter than dogs";
line2 = "dogs also like meat";

if ( line1 =~ /cats(.*)/ )
 puts "line1 starts with cats"
end
if ( line2 =~ /cats(.*)/ )
 puts "line2 starts with dogs"
end

这将产生以下结果:

line1 starts with cats

正则表达式修饰符:

正则表达式的文字可以包括一个可选的修饰符来控制各方面的匹配。修改指定第二个斜杠字符后,如前面所示,可表示为这些字符之一:

201551393809550.jpg (572×316)

 %q分隔字符串文字一样,ruby允许正则表达式带 %r,然后由所选择的定界符。这是非常有用的,当所描述的模式中包含正斜杠字符不希望转义:

# following matches a single slash character, no escape required
%r|/|        

# flag characters are allowed with this syntax, too
%r[</(.*)>]i 

正则表达式模式:

除控制字符, (+ ? . * ^ $ ( ) [ ] { } | \), 所有字符匹配。可以转义控制字符前面加上反斜线。

 搜索和替换:

string方法最重要的,使用正则表达式sub 和 gsub,他们就地变种sub! 和 gsub!

所有这些方法执行搜索和替换操作过程中使用一个正则表达式模式。sub & sub!替换第一次出现的模式 gsub & gsub!替换所有出现。

sub! 和 gsub! 返回一个新的字符串,未经修改的原始 sub 和 gsub 他们被称为修改字符串。

下面的例子:

#!/usr/bin/ruby

phone = "2004-959-559 #this is phone number"

# delete ruby-style comments
phone = phone.sub!(/#.*$/, "")  
puts "phone num : #{phone}"

# remove anything other than digits
phone = phone.gsub!(/\d/, "")  
puts "phone num : #{phone}"

这将产生以下结果:

phone num : 2004-959-559
phone num : 2004959559

下面是另一个例子:

#!/usr/bin/ruby

text = "rails are rails, really good ruby on rails"

# change "rails" to "rails" throughout
text.gsub!("rails", "rails")

# capitalize the word "rails" throughout
text.gsub!(/\brails\b/, "rails")

puts "#{text}"

这将产生以下结果:

rails are rails, really good ruby on rails

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网