2016-03-12 71 views
0

此代碼:NSPredicate的正則表達式模式匹配崩潰

internal let emailRegex:String = "[A-Z0-9a-z._%+-]+[A-Za-z0-9.-]+\\.[A-Za-z]{2,5}" 

let emailText = NSPredicate(format: "SELF MATCHES \(emailRegex)") 

return emailText .evaluateWithObject(email) 

崩潰,出現錯誤:

'NSInvalidArgumentException', reason: 'Unable to parse the format string "SELF MATCHES [A-Z0-9a-z._%+-]+[A-Za-z0-9.-]+.[A-Za-z]{2,5}"'

+0

的電子郵件驗證一些良好的閱讀,也可以不幫助你解決問題,但它可以幫助你避免其他人:[我知道如何驗證Em所有地址直到我讀了RFC](http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/) – ColGraff

回答

1

此外,你的我有另一個電子郵件正則表達式,你可以去。

func isValidEmail() -> Bool { 

    let regex = NSRegularExpression(pattern: "^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,4}$", 
       options: [.CaseInsensitive]) 

    return regex.firstMatchInString(self, options:[], 
     range: NSMakeRange(0, emailString.characters.count)) != nil 
} 

請檢查這個正則表達式。

+0

can你請解釋什麼是utf16.count? –

+0

thanx它的工作原理是將utf16.count更改爲email.characters.count –

+0

@Sohil R. Memon將向我解釋'試試!'在'let regex ='語句中表示。 –

1

下面是正則表達式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! 
0

終於讓我找到了問題的解決方案通過

func isValidEmail(email:String) -> Bool 
{ 


    let regex = try! NSRegularExpression(pattern: "^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,4}$", 
     options: [.CaseInsensitive]) 

    return regex.firstMatchInString(email, options:[], 
     range: NSMakeRange(0, email.characters.count)) != nil 


}