Regular expression for password

Can someone give me a regex for password with the following rules.

Password must contain at least 7 characters. It must contain at least 3 digits and one alphabetic character. The password can accept numbers, alphabets, special characters any number of times, with the exception of numbers, must be at least 3.

0
source share
5 answers

Regular expressions are not particularly good at the fact that certain groups of characters appear a certain number of times. Although this is probably possible - it will no doubt be curtailed and not obvious.

If you are programming in .NET (C # or VB), you can use a simple check function, for example:

bool ValidatePasswordCompliance( string password ) { int countDigits = 0; int countAlpha = 0; int countOthers = 0; foreach( char c in password ) { countDigit += c.IsDigit ? 1 : 0; countAlpha += c.IsAlpha ? 1 : 0; countOther += !(c.IsAlpha || c.IsDigit) ? 1 : 0; } return countDigits >= 3 && (countDigits + countAlpha + countOthers) >= 7; } 

If you are working with .NET 3.5 or higher, you can use LINQ to simplify this:

 bool ValidatePasswordCompliance( string password ) { return password.Count() >= 7 && password.Count( x => x.IsDigit ) >= 3; } 
+8
source

This is better suited to a validation function that validates your individual criteria one by one than an overly complex regex.

If you are trying to use regex, look at this almost identical question ... but read the highest voice response, not just the accepted one.

+4
source

Regular expressions, while elegant, if done correctly, are not suitable for all purposes. I would suggest that this is one of those cases when it does not fit.

Do not get me wrong, you can do it with one RE, but it can be much more complicated and more difficult to maintain than a simple procedural one that checks the length and character classes.

+2
source

However, there are people who actually do this with regular expressions (although they also recognize that it is difficult)

http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C4F005D3717

+1
source

You can easily check for complexity with regex, but this is not the end ...

A good article on setting up the various complexities you are looking for:

http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/

You may also need to run the password for a simple dictionary to find out if it can be circumvented by a dictionary attack.

0
source

All Articles