tags:

views:

295

answers:

5

Please can some one give me regular expression for password with the following rules.

Password should be at least 7 characters long. It should contain minimum 3 digits and one alphabetic character. Password can accept numbers, alphabets, special characters any number of times except numbers should be minimum 3.

+4  A: 

This is better suited to a validation function that checks your individual criteria one-by-one than an overly complicated regex.

If you're hellbent on using a regex, take a look at this almost identical question... but read the highest voted answer, not just the accepted one.

ceejayoz
+2  A: 

Regular expressions, while elegant if done right, are not fit for all purposes. I would suggest that this is one of the cases it is not suited for.

Don't get me wrong, you can do it with a single RE, but it's likely to be far more complex and hard to maintain than some simple procedural which checks the length and character classes.

paxdiablo
+7  A: 

Regular expressions aren't particularly good at ensuring that particular groups of characters appear a certain number of times. While it's probably possible - it would no doubt be convoluted and non-obvious.

If you're programming in .NET (C# or VB) you can use a simple validation function something like:

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're working with .NET 3.5 or higher, you could use LINQ to simplify this:

bool ValidatePasswordCompliance( string password )
{
    return password.Count() >= 7 &&
           password.Count( x => x.IsDigit ) >= 3;
}
LBushkin
Voting up since it gives sample code.
paxdiablo
I would note, that a real world password validation function may want to check for any reserved characters that are not valid as password characters - particularly if it is intended to work in a multi-language environment like the web.
LBushkin
Regex can be challenging and rewarding when you craft one that works well but not always the answer. Up vote for pragmatism.
JustSmith
+1  A: 

That said, there are some people out there who actually do it with regular expressions (although they too admit that it's complicated)

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

Robert Harvey
A: 

You can check complexity with regex pretty easily, but its not an end all...

Good article on setting up the different complexities you are looking for:

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

You also might want to run the password against a simple dictionary, to see if it can be bypassed by a dictionary attack.

BigBlondeViking