📜  Ruby-正则表达式

📅  最后修改于: 2020-10-16 05:59:20             🧑  作者: Mango


正则表达式是字符的特殊序列,可帮助您匹配或查找使用的模式举办了专门的语法字符串的其他字符串或设置。

正则表达式字面量是斜线之间或任意定界符之间的模式,后跟%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 contains Cats"
end
if ( line2 =~ /Cats(.*)/ )
   puts "Line2 contains  Dogs"
end

这将产生以下结果-

Line1 contains Cats

正则表达式修饰符

正则表达式字面量可以包括可选的修饰符,以控制匹配的各个方面。如前所示,修饰符在第二个斜杠字符之后指定,并且可以用以下字符之一表示-

Sr.No. Modifier & Description
1

i

Ignores case when matching text.

2

o

Performs #{} interpolations only once, the first time the regexp literal is evaluated.

3

x

Ignores whitespace and allows comments in regular expressions.

4

m

Matches multiple lines, recognizing newlines as normal characters.

5

u,e,s,n

Interprets the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding.

像用%Q分隔的字符串字面量一样,Ruby允许您以%r开头正则表达式,后跟您选择的分隔符。当您描述的模式包含许多不想转义的正斜杠字符时,这很有用-

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

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

正则表达式

除控制字符(+?。* ^$()[] {} | \)外,所有字符匹配。您可以在控制字符前面加上反斜杠来对其进行转义。

正则表达式示例

搜索和替换

一些使用正则表达式的最重要的String方法是subgsub ,以及它们的就位变体sub!gsub!

所有这些方法都使用Regexp模式执行搜索和替换操作。子!替换模式的第一个匹配项以及gsubgsub!替换所有事件。

subgsub返回一个新的字符串,而原来的未修改的位置保留为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