CQM
CQM

Reputation: 44200

Java String.matches() regular expressions

I am trying to use the matches() function to check a user-entered password for certain conditions

"Contains six alphanumeric characters, at least one letter and one number"

Here is my current condition for checking for alphanumeric characters

pword.matches("([[a-zA-Z]&&0-9])*")

unfortunately in example using "rrrrZZ1" as the password this condition still returns false

What would be the correct regular expression? Thank you

Upvotes: 0

Views: 4108

Answers (2)

Mike Causer
Mike Causer

Reputation: 8314

I agree with ziesemer - use a validatePassword() method instead of cramming it into regex.

Much more readable for a developer to maintain.

If you do want to go down the regex path, it is achievable using zero width positive lookaheads.

Contains six characters, at least one letter and one number:

^.*(?=.{6,})(?=.*[a-zA-Z]).*$

I changed your six alphanumeric characters to just characters. Supports more complex passwords :)

Great post on the topic:

http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/

Bookmark this one too:

http://www.regular-expressions.info/

Upvotes: 2

ziesemer
ziesemer

Reputation: 28687

Someone else here may prove me wrong, but this is going to be very difficult to do without an excessively complex regular expression. I'd just use a non-regular expression approach instead. Set 3 booleans for each of your conditions, loop through the characters and set each boolean as each condition is met, and if all 3 booleans don't equal true, then fail the verification.

You could use something as simple as this:

public boolean validatePassword(String password){
    if(password.length() < 6){
        return false;
    }
    boolean foundLetter = false;
    boolean foundNumber = false;
    for(int i=0; i < password.length(); i++){
        char c = password.charAt(i);
        if(Character.isLetter(c)){
            foundLetter = true;
        }else if(Character.isDigit(c)){
            foundNumber = true;
        }else{
            // Isn't alpha-numeric.
            return false;
        }
    }
    return foundLetter && foundNumber;
}

Upvotes: 5

Related Questions