Reputation: 7979
What could be the reg ex for the above criteria?
I am creating a check for stronger password :)
c# i am using
Upvotes: 8
Views: 8711
Reputation: 8560
This should do it:
(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).{8,}
See here: rubular
Explained:
(?=.*?[a-z]) //lookahead, there has to be a lower case alphabetic char
(?=.*?[A-Z]) //lookahead, there has to be a upper case alphabetic char
(?=.*?[^a-zA-Z]) //lookahead, there has to be a non-alphabetic char
.{8,} // any character at least 8 times
Upvotes: 14
Reputation: 386210
Don't try to use one regexp for all rules -- it's hard, and more importantly it will be hard to read and modify by future programmers. Instead, write one function for each rule. Use a string length function for the first rule, then use separate regular expressions (or a simple scan of the string)for uppercase letters, lowercase letters and numbers.
Your test then becomes something like:
if (len(password) >= 8 &&
contains_lower(password) &&
contains_upper(password) &&
contains_number(password)) {
...
}
Your code becomes absolutely clear in its intent, and if you have to change just one piece of the algorithm you don't have to reinvent a complex regular expression. Plus, you'll be able to unit test each rule independently.
Compare that to an example someone wrote in another answer to this question:
(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).{8,}
Which of these two answers looks easier to understand, easier to modify and easier to test? You can't even guess what the regex is doing until you spend a few (or many) moments studying it. And what if the requirement changes to ".. and has at least one underscore"? How do you change the pattern, especially when you weren't the one who came up with the pattern to begin with?
Upvotes: 12