2

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?

Donut
  • 110,061
  • 20
  • 134
  • 146
BabelFish
  • 899
  • 2
  • 9
  • 20
  • possible duplicate of [Help with password complexity regex](http://stackoverflow.com/questions/2582079/help-with-password-complexity-regex) – Frédéric Hamidi Oct 29 '10 at 20:36

3 Answers3

2
^(?=.*[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
  • 328,213
  • 58
  • 503
  • 561
0

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
  • 129,300
  • 32
  • 216
  • 265
  • 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 Oct 29 '10 at 20:37
  • @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 Oct 29 '10 at 20:39
  • 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 Oct 29 '10 at 20:44
  • @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 Oct 29 '10 at 20:46
0
bool valid =  
    Regex.IsMatch(password, @"\w+")// add additional allowable characters here
    && Regex.IsMatch(password, @"\d")
    && Regex.IsMatch(password, @"\p{Lu}");
Seattle Leonard
  • 6,548
  • 3
  • 27
  • 37