2014-10-06 201 views
0

我有一個重複的string="I will email you at [email protected]",我只想拿出實際的電子郵件地址。如何從紅寶石字符串中提取子字符串?

如何才能將電子郵件取出?

注意:理想情況下,我還想處理格式可能爲"I will email you at my email [email protected]"的用戶錯誤。在這種情況下,用戶輸入「我的電子郵件[email protected]」,我只想要電子郵件地址。

+2

'string.scan(/ easy/easy easy googlable regex for email here /)' – 2014-10-06 20:44:59

回答

1

相對寬鬆的正則表達式這一主題,將與你的榜樣工作的一些良好的閱讀:也

"I will email you at [email protected]".match(/\b\[email protected]\S+\b/).to_s 
#=> "[email protected]" 

見這RFC-compliant regex

+1

+1指向Parrot RFC兼容模式。 – 2014-10-06 23:42:50

+0

很好,讓我檢查一下 - 如果有人輸入一個壞的字符串電子郵件....它將是零? – Angela 2014-10-07 05:38:45

+0

由於我們正在投射MatchData對象,它將是空的,而不是零。 '「找不到」.match(/ \ b \ S + @ \ S + \ b /).to_s.empty? == true' – 2014-10-07 14:23:23

0

你可以這樣做:

[6] pry(main)> string="I will email you at [email protected]" 
=> "I will email you at [email protected]" 
[7] pry(main)> string.scan(/[A-Za-z\d_\-\.+][email protected][A-Za-z\d_\-\.]+\.[A-Za-z\d_\-]+/) 
=> ["[email protected]"] 
[8] pry(main)> str2 = "I will email you at my email [email protected]" 
=> "I will email you at my email [email protected]" 
[9] pry(main)> string.scan(/[A-Za-z\d_\-\.+][email protected][A-Za-z\d_\-\.]+\.[A-Za-z\d_\-]+/) 
=> ["[email protected]"] 

附近的那家 「How to Find or Validate an Email Address

相關問題