2014-11-04 42 views
0

我試圖做一個正則表達式,消除在我文字中的電子郵件email: [email protected]剛剛捕獲文本,並用正則表達式

例如:I ​​request information on your project email: [email protected]
所以我這樣做,抓住我「電子郵件: [email protected]

message ="I ​​request information on your project email. [email protected]" 
message.gsub!("/(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i") 

它返回我什麼,我想有隻在消息文本中。

感謝

+3

在您的示例消息中沒有'email:'only'ema il.'存在。 – Bala 2014-11-04 11:17:40

回答

0

你的代碼中有幾個問題:

  • 您正在尋找"email: ...",但你消息有"email. ..."
  • 您使用gsub!,使用一個參數,這不是經典用例,並返回Enumerator。經典的用例需要一個第二個參數,它表示您要替換找到的匹配內容:

    執行字符串#GSUB到位的替代,返回海峽,或 零,如果進行沒有換人。 如果沒有給出塊並且沒有替換 ,則返回枚舉器而不是

  • 你傳遞一個字符串gsub! - "/(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i",這是不同比發送一個正則表達式。要通過一個正則表達式,你需要刪除它周圍的報價:/(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i

所以修復你的代碼應該是這樣的:

message ="I ​​request information on your project email: [email protected]" 
message.gsub!(/(email: [-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$)/i, '') 
# => "I ​​request information on your project " 

另外請注意,我改變你的代碼,使用gsub代替gsub!,因爲gsub!更改了底層字符串,而不是創建一個新字符串,除非您有充足的理由這樣做,否則不鼓勵對輸入參數進行變異...

0

如果要刪除從文本的電子郵件使用String#sub

message = "I ​​request information on your project email. [email protected]" 
message.sub!(/[A-Za-z]{5}:\s[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}/, '') 
# => "I ​​request information on your project " 
+0

我只想得到的文本,而不是電子郵件:[email protected] – user1774481 2014-11-04 11:51:02

+0

請參考我上面編輯的代碼。 – Benji 2014-11-04 11:56:29

1

試試這個。這應該適用於大寫字母,小寫字母和電子郵件出現在字符串的中間。

email = /[A-Za-z]{5}:\s[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}/ 

s = "I request information on your project email: [email protected]" 
s.match(email).pre_match  #=> "I request information on your project " 

s2 = "This email: [email protected] is in the middle" 
s2.match(email).pre_match #=> "This " 
s2.match(email).post_match #=> " is in the middle" 

但還有更多案例未涉及email:其次是許多空間

相關問題