views:

57

answers:

4

I can't seem to get this to work.

I am looking for a regular expression that will validate a password. Allowable characters are a-zA-Z0-9, but the sequence must have at least 1 number and 1 capital letter.

Can this be done?

+2  A: 
^(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]+$

should do.

^             # start of string 
(?=.*[A-Z])   # assert that there is at least one capital letter ahead
(?=.*[0-9])   # assert that there is at least one digit ahead
[A-Za-z0-9]+  # match any number of allowed characters 
              # Use {8,} instead of + to require a minimum length of 8 characters.
$             # end of string
Tim Pietzcker
A: 

You can use non-zero-width lookahead/lookbehind assertions in regex. For instance:

^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$

Requires that there exist at least one number, one lowercase and one uppercase letter. Using \w allows you to accept non-English or accented characters (which you may or may not want to allow). Otherwise use [a-zA-Z] instead.

LBushkin
This allows a lot more than the OP wanted (`\w` is Unicode-aware in .NET) - although of course restricting valid letters for a *password* doesn't make much sense either.
Tim Pietzcker
@Tim Pietzcker: Yes, I know. I mention that `\w` will accept accented and international word characters from the unicode set. It's an alternative to using the [a-zA-Z] construct.
LBushkin
Sorry, I didn't read your answer carefully enough. But `\w` also matches digits and the underscore (and other "word-continuating punctuation" characters).
Tim Pietzcker
@Time Pietzcker: Yes, which is why `\d` is in their. I think your answer is better anyway - separating the two ZPL assertions makes more sense than what I suggest.
LBushkin
A: 
bool valid =  
    Regex.IsMatch(password, @"\w+")// add additional allowable characters here
    && Regex.IsMatch(password, @"\d")
    && Regex.IsMatch(password, @"\p{Lu}");
Seattle Leonard