舉例初步講解Ruby中的Regex
這篇文章主要介紹了Ruby中的Regex,是Ruby學習進階當中的重要知識,需要的朋友可以參考下
Regex是一個特殊的字元序列可以協助匹配或者找到其他字串或串套,使用的模式保持一個專門的文法。
Regex文本是一個模式之間的斜線之間或任意分隔字元 %r 如下:
文法:
複製代碼 代碼如下:
/pattern/
/pattern/im # option can be specified
%r!/usr/local! # general delimited regular expression
例如:
?
|
1
2
3
4
5
6
7
8
9
10
11 |
#!/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
|
這將產生以下結果:
?
Regex修飾符:
Regex的文字可以包括一個可選的修飾符來控制各方面的匹配。修改指定第二個斜杠字元後,如前面所示,可表示為這些字元之一:
%Q分隔字串文字一樣,Ruby允許Regex帶 %r,然後由所選擇的定界符。這是非常有用的,當所描述的模式中包含正斜杠字元不希望轉義:
?
|
1
2
3
4
5 |
# Following matches a single slash character, no escape required
%r|/|
# Flag characters are allowed with this syntax, too
%r[</(.*)>]i
|
Regex模式:
除控制字元, (+ ? . * ^ $ ( ) [ ] { } | ), 所有字元匹配。可以轉義控制字元前面加上反斜線。
搜尋和替換:
String方法最重要的,使用Regexsub 和 gsub,他們就地變種sub! 和 gsub!
所有這些方法執行搜尋和替換操作過程中使用一個Regex模式。sub & sub!替換第一次出現的模式 gsub & gsub!替換所有出現。
sub! 和 gsub! 返回一個新的字串,未經修改的原始 sub 和 gsub 他們被稱為修改字串。
下面的例子:
?
|
1
2
3
4
5
6
7
8
9
10
11 |
#!/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}"
|
這將產生以下結果:
?
|
1
2 |
Phone Num : 2004-959-559
Phone Num : 2004959559
|
下面是另一個例子:
?
|
1
2
3
4
5
6
7
8
9
10
11 |
#!/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!(/brailsb/, "Rails")
puts "#{text}"
|
這將產生以下結果:
?
|
1 |
Rails are Rails, really good Ruby on Rails
|