guest_rg said:I am new to regular expressions and I need a regular expression for an important task. The requirement is for a password string with:
8 to 20 chars long
2 chars must be capitals, special characters or numbers
Thanks in advance
Richard Crist said:I believe you will have to verify the length using .NET's String.Length, but you can check for the other stuff using something like this:
[0-9A-Z!-@].*[0-9A-Z!-@]
If you don't find the above string in your password then it fails the character test. This regular expression amounts to the following:
Find an occurrence of a digit, capital letter, or special symbol followed by anything followed by another digit, capital letter, or special symbol. In other words, find at least one of your desired characters followed eventually by another one.
There may be other ways using :digit: and other identifiers, but the above method is one I use for tasks like yours. The square brackets [] are used to represent the occurrence of one (1) character that is one of the characters in the list inside the square brackets. If you wanted to negate the search you would use something like:
[^A-Za-b]
which means no alphabetic characters. The caret ^ symbol at the beginning of the bracketed list means "none of these".
Hope this helps.
guest_rg said:Richard,
This is helpful but I was hoping that there would be a way to perform all the checks in one expression. The password format check is going to be database driven. I want it to be dynamic. If I make the length check using String.Length, I will have to make coding changes if the requirement changes.
Everybody, Please let me know if there is a answer to this.
Thanks
guest_rg said:Well...then I will check for the rules in multiple RegExp's. Please tell me if these individual RegExp's are correct.
-- String that is 8 to 20 chars long.
^(?=.*).{8,20}$
-- 2 chars must be capitals, special characters or numbers. In other words, this can be interpreted as the string contains atleast 2 chars that are not small letters.
^(?=[^a-z].*[^a-z])$
Thanks