Regular expression, or condition not working in Swift but works on online debuggers

Viewed 1141

I am trying to check if string contains one extra character OR one digit. But for some reason it doesn't work in Swift but it works on online debuggers/editors.

This is my regex: ^(?=.*[a-z])(?=.*[$@$#!%*?&])|(?=.*[0-9]).{6,}

As I understand then:

^ - this is start anchor
(?=.*[a-z]) - string has one character
(?=.*[$@$#!%*?&]) - string has one special character
(?=.*[0-9]) - string has one digit
{6,} - string length is at least 6

and in regex validations the regular | symbol symbolises OR condition.

My question is that why the output is not what I want?

stackoverflow - false
stackoverflow1 - true 
stackoverflow@ - false // should be true
stackoverflow1@ - false // should be true

This is what I do in swift:

func isPasswordValid(_ password : String) -> Bool{
    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[a-z])(?=.*[$@$#!%*?&])|(?=.*[0-9]).{6,}$")
    return passwordTest.evaluate(with: password)
}

To be clear, this is what I want: String must be at least 6 characters long and has at least one digit OR extra character. It would be good not to limit the characters to only (?=.*[$@$#!%*?&])

1 Answers
Related