tags:

views:

414

answers:

3

Can anyone help me write a regular expression for checking if a password has at least one letter and one number in it?

I have a requirement that users passwords must be alphanumeric and I want to be able to check for that using a regular expression.

+2  A: 
bool isValid = Regex.IsMatch(password, @"[a-zA-Z]") &&
               Regex.IsMatch(password, @"\d");
Jason
\\w actually contains digits and underscores too, so it will not work as intended
sepp2k
\w matches _
eyelidlessness
D'oh, beaten by 26 seconds.
eyelidlessness
Thanks, edited.
Jason
Yeah, but it is appropriate too, sinse the objective is not allowing "easy" password like those having only numbers or only letters, placing some symbols is even more safe.
Havenard
Adding @ before a quoted string makes it so you don't have to escape every backslash. It makes for much more readable regular expressions.Ex: @"[a-zA-Z].*\d"
Bryce Kahle
Clarified even further, and will likely run faster too.
Jason
Havenard, while that is probably true, the fact of the matter is it didn't quite meet the requirements requested by PingPongBongo.
eyelidlessness
+6  A: 

If you want it in one regex you can use "[a-zA-Z].*\\d|\\d.*[a-zA-Z]" though two seperate checks may be more readable.

Edit: An approach with two checks, which I find quite readable, might look like this:

Regex.IsMatch(password, "\\d") && Regex.IsMatch(password, "[a-zA-Z]")
sepp2k
And then you'd need an extra check to test if it has alphanumeric characters only.
JG
+4  A: 

Positive lookahead is what you're looking for. The regex looks like this:

(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+

Here, (?=.*[A-Za-z]) is the positive lookahead which asserts that your string as at least one character, and (?=.*[0-9]) asserts that it has at least one digit. It's important to note that the positive lookahead doesn't return a match, but rather asserts whether a match exists or not. So, you should read the previous regex as "assert that it has at least one character; assert it has at least one digit; now that we know the assertions have passed, just check for alphanumeric characters".

This is very interesting because it allows you to easily combine the validation requirements of your application, without making your regex very complex. For example, if you now require the string to have exactly 20 characters, you just need to add a new positive lookahead assertion, like so:

(?=[A-Za-z0-9]{20})(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+

Hope it helps!

JG