下面是正則表達式I Knew How To Validate An Email Address Until I Read The RFC
import Foundation
let pattern = "^(?!\\.)(\"([^\"\\r\\\\]|\\\\[\"\\r\\\\])*\"|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\\.)\\.)*)(?<!\\.)@[a-z0-9][\\w\\.-]*[a-z0-9]\\.[a-z][a-z\\.]*[a-z]$"
let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
// tests in the format (email, isValid)
let tests = [
("NotAnEmail", false),
("@NotAnEmail", false),
("\"test\\\rblah\"@example.com", true),
("\"test\rblah\"@example.com", false),
("\"test\\\"blah\"@example.com", true),
("\"test\"blah\"@example.com", false),
("customer/[email protected]", true),
("[email protected]", true),
("!def!xyz%[email protected]", true),
("[email protected]", true),
("[email protected]", true),
("[email protected]", false),
("[email protected]", false),
("[email protected]", false),
("[email protected]", false),
("\"[email protected]\"@example.com", true),
("[email protected]", true),
("\"Ima.Fool\"@example.com", true),
("\"Ima Fool\"@example.com", true),
("Ima [email protected]", false)]
for (index,(email,isValid)) in tests.enumerate() {
let eval = predicate.evaluateWithObject(email)
if eval == isValid {
print(index, ": VALID!")
}
}
輸出:
0 : VALID!
1 : VALID!
2 : VALID!
3 : VALID!
4 : VALID!
5 : VALID!
6 : VALID!
8 : VALID!
10 : VALID!
11 : VALID!
12 : VALID!
13 : VALID!
14 : VALID!
15 : VALID!
17 : VALID!
18 : VALID!
19 : VALID!
的電子郵件驗證一些良好的閱讀,也可以不幫助你解決問題,但它可以幫助你避免其他人:[我知道如何驗證Em所有地址直到我讀了RFC](http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/) – ColGraff