1

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Worked, about the lowercase... was my mistake, i also check for at least one lowercase, i am not going to edit the question so your answer keeps making sense, might help someone running into the same issue.
You are welcome and I thank you for accepting and upvoting the answer but you although have to note that the other answer mentions another important point: adding ^ and $!
3

Your regex is wrong, use the following regex:

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

DEMO

enter image description here

1 Comment

@JuanPabloBoero , I see, I'm not soo familiar with Swift flavor of regex :), replacing \dwith \\d in answer anyway :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.