正则表达式是一个特殊的字符序列可以帮助匹配或者找到其他字符串或串套,使用的模式保持一个专门的语法。
正则表达式文本是一个模式之间的斜线之间或任意分隔符 %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
正则表达式修饰符:
正则表达式的文字可以包括一个可选的修饰符来控制各方面的匹配。修改指定第二个斜杠字符后,如前面所示,可表示为这些字符之一:
%Q分隔字符串文字一样,Ruby允许正则表达式带 %r,然后由所选择的定界符。这是非常有用的,当所描述的模式中包含正斜杠字符不希望转义:
# Following matches a single slash character, no escape required %r|/| # Flag characters are allowed with this syntax, too %r[</(.*)>]i
正则表达式模式:
除控制字符, (+ "htmlcode">
#!/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