舉例初步講解Ruby中的Regex

來源:互聯網
上載者:User

舉例初步講解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

  這將產生以下結果:

  ?

1

Line1 starts with Cats

  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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.