Juan Boero
Juan Boero

Reputation: 6427

Swift regular expression usage

I cannot convert this Java regular expression to swift:

^(?=.[a-z])(?=.[A-Z])(?=.*\d).{6,15}$

It basically checks for the input to have at least one uppercase, at least a number, and a minimum length of 6 characters and a maximum of 15.

The input to check against cames from a UITextField , and i have this function to check against:

func isValidPassword(candidate: String) -> Bool {
    let passwordRegex = "(?=.[a-z])(?=.[A-Z])(?=.*\\d).{6,15}"

    return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluateWithObject(candidate)
}

Then, in my logic i do something like this:

if isValidPassword(textField.text) {
    println("password is good")
} else {
    println("password is wrong")
}

I am always getting that wrong password log.

I even tried modifying the expression with this Cheat Sheet with no luck.

Anyone can spot the flaw in the regular expression?

Upvotes: 1

Views: 3764

Answers (2)

Pruthvi Raj
Pruthvi Raj

Reputation: 3036

Your regex is wrong, use the following regex:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{6,15}$

DEMO

enter image description here

Upvotes: 3

luk2302
luk2302

Reputation: 57184

I think your regex is wrong. It should be (?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{6,15} - note the * before [a-z] and before [A-Z]. It follows the same principles you already applied to the digit-group.

Still that does not fit your description because it forces a lowercase letter as well. You might want to remove the first (?=) group or change your expectation / description.

Upvotes: 3

Related Questions