Search code examples
iosregexswiftnspredicate

NSPredicate for regex pattern matching crashes


This code:

 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)

Crashes with error:

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


Solution

  • Besides, your's I have another email regex which you can go for.

    func isValidEmail() -> Bool {
    
        let regex = NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$",
                    options: [.CaseInsensitive])
    
        return regex.firstMatchInString(self, options:[],
            range: NSMakeRange(0, emailString.characters.count)) != nil
    }
    

    Please check this regex.