舉例初步講解Ruby中的Regex_ruby專題

來源:互聯網
上載者:User

 Regex是一個特殊的字元序列可以協助匹配或者找到其他字串或串套,使用的模式保持一個專門的文法。

Regex文本是一個模式之間的斜線之間或任意分隔字元 %r 如下:
文法:

複製代碼 代碼如下:
/pattern/
/pattern/im    # option can be specified
%r!/usr/local! # general delimited regular expression

例如:

#!/usr/bin/rubyline1 = "Cats are smarter than dogs";line2 = "Dogs also like meat";if ( line1 =~ /Cats(.*)/ ) puts "Line1 starts with Cats"endif ( line2 =~ /Cats(.*)/ ) puts "Line2 starts with Dogs"end

這將產生以下結果:

Line1 starts with Cats

Regex修飾符:

Regex的文字可以包括一個可選的修飾符來控制各方面的匹配。修改指定第二個斜杠字元後,如前面所示,可表示為這些字元之一:

 %Q分隔字串文字一樣,Ruby允許Regex帶 %r,然後由所選擇的定界符。這是非常有用的,當所描述的模式中包含正斜杠字元不希望轉義:

# 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 他們被稱為修改字串。

下面的例子:

#!/usr/bin/rubyphone = "2004-959-559 #This is Phone Number"# Delete Ruby-style commentsphone = phone.sub!(/#.*$/, "")  puts "Phone Num : #{phone}"# Remove anything other than digitsphone = phone.gsub!(/\D/, "")  puts "Phone Num : #{phone}"

這將產生以下結果:

Phone Num : 2004-959-559Phone Num : 2004959559

下面是另一個例子:

#!/usr/bin/rubytext = "rails are rails, really good Ruby on Rails"# Change "rails" to "Rails" throughouttext.gsub!("rails", "Rails")# Capitalize the word "Rails" throughouttext.gsub!(/\brails\b/, "Rails")puts "#{text}"

這將產生以下結果:

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.