Link to home
Start Free TrialLog in
Avatar of Sandy209
Sandy209

asked on

Regex for alphanumeric only


* must contain both upper and lowercase characters
* must contain at least one number
* must only contain letters and numbers (no other special characters)
* min length 7, max length 12

The following is close:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*[@#$%^&+=]).{7,12}$

but there is a danger i could miss characters in the exclude list.  Is there anyway to specify just alphanumeric only?

Thanks
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])([0-9a-zA-Z]){7,12}$
ASKER CERTIFIED SOLUTION
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sandy209
Sandy209

ASKER

Excellent!  Thanks
I would not use regex in this case. Finite state machine would be much simpler.

Something like:

bool upperCaseFound = false;
bool lowerCaseFound = false;
bool digitFound = false;

foreach (char c in s)
{
    switch (char.GetUnicodeCategory(c))
    {
        case UnicodeCategory.UppercaseLetter:
            upperCaseFound = true;
            break;

        case UnicodeCategory.LowercaseLetter:
            lowerCaseFound = true;
            break;

        case UnicodeCategory.DecimalDigitNumber:
            digitFound = true;
            break;
    }
}

bool validPassword =
    lowerCaseFound &&
    upperCaseFound &&
    digitFound &&
    s.Length >= 7 &&
    s.Length <= 12;