Search code examples
iosobjective-cswiftnspredicate

Swift NSPredicate evaluate fails


I'm new to using Regex and NSPredicates. I'm trying to convert below objective code to swift and it fails with following error:

'NSInvalidArgumentException', reason: 'Can't do regex matching on object SELF MATCHES ".+@([A-Za-z0-9-]+\.)+[A-Za-z]{2}[A-Za-z]*".'

Objective C code:

- (BOOL)validateEmailWithString:(NSString*)userEmail
{
    BOOL stricterFilter = NO;
    NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:userEmail];
}

Equivalent Swift Code

func validateEmail(withString userEmail: String) -> Bool {
        let stricterFilter: Bool = false
        let stricterFilterString: String = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
        let laxString: String = ".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*"
        let emailRegex: String = stricterFilter ? stricterFilterString : laxString
        let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: emailTest)
    }

Exception occurs at this line:

return emailTest.evaluate(with: emailTest)

Objective C code works fine, but in swift the app crashes. Can someone please help me with this?


Solution

  • Please used this line and test it

    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
    
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailTest.evaluateWithObject(userEmail)