2017-07-08 32 views
-1

我剛開始學習如何使用Regex,我試圖創建一個正則表達式來驗證Ruby中的電子郵件地址。這是我走到這一步:電子郵件驗證問題Ruby上的Regex

emailregex = /([a-zA-Z]+([_\-.][a-zA-Z]*)*@\D+[.]\D+)/ 
str = "[email protected]" 
puts str.scan emailregex 

預期輸出:

[email protected] 

實際輸出:

[email protected] 
_def 

我已經看到了一些電子郵件正則表達式驗證,但我想知道我的正則表達式有什麼問題。謝謝你的建議。

+0

你可以使用防禦過濾器正則表達式的第一線,從http://www.w3.org/TR/html5/forms.html#valid-e-mail-address,這是:[a-zA-Z0-9](?:[a-zA-Z0-9。!#$%&'* +/=?^ _ \'{|}〜 - ] + ZA-Z0-9 - ] {0,61} [A-ZA-Z0-9])(?:??\ [A-ZA-Z0-9](在[a-ZA-Z0-9-] {0,61} [a-zA-Z0-9])?)* $'然後發送驗證郵件。 – sln

回答

0

如果在正則表達式中至少有一個捕獲組(...),掃描將僅輸出捕獲組。

該正則表達式有2個捕獲組,_def是內部捕獲組的最後一次發生。
你可以讓內部的一個非捕獲組(?:...)來避免這一點。

例如:

str = "emails : [email protected] [email protected]" 
emailregex = /([a-zA-Z]+(?:[_.-][a-zA-Z]*)*@\S+[.]\S+)/ 
puts str.scan emailregex 

輸出:

[email protected] 
[email protected] 

順便說一下,掃描可以是有用的,以基於圖案的文本獲得匹配的陣列。
但實際驗證字符串模式?還有另一種方法。

例子:

emailregex = /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-][email protected][a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i 

puts ("[email protected]" =~ emailregex ? true : false) 

puts ("Joda.says:email.is.not" =~ emailregex ? true : false) 
+0

值得一提的是,'String#scan'總是返回一個數組,即使'puts'只輸出一個字符串。 – mudasobwa

+0

感謝您的幫助! –

2

這是String#scan不是Regexp,誰是責任。檢查:

str = "[email protected]" 
str.scan /\w+/ 
#⇒ ["abc_def", "hotmail", "com"] 

您可能想要使用String#[]

str[emailregex] 
#⇒ "[email protected]" 

但是,請不要使用正則表達式匹配電子郵件和here is why。遲早你的基於正則表達式的驗證將失敗。要驗證電子郵件地址,只需在字符串中檢查@,然後將驗證電子郵件發送給。這是驗證電子郵件的唯一有效的現代方式。