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?
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?
^(?=.*[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
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.
This is very close:
http://stackoverflow.com/questions/1051989/regex-for-alphanumeric-but-at-least-one-character
bool valid =
Regex.IsMatch(password, @"\w+")// add additional allowable characters here
&& Regex.IsMatch(password, @"\d")
&& Regex.IsMatch(password, @"\p{Lu}");