How can I create a regex to test username complexity requirements?

I study regular expressions and ask one question; the answer will help me better understand regular expressions.

Input is the username. This username must contain at least 4 lowercase characters (az), one upper char (AZ), and 2 numbers. It must also contain no more than 10 characters. How can I make a regex to test these requirements?

+4
source share
2 answers

Use regex with lookaheads / lookbehinds for each condition. Something like below:

^(?=(.*[az]){4})(?=.*[AZ])(?=(.*\d){2}).{7,10}$ 

I think the regex is self-evident, tell me if you want me to explain each part.

Ok, explanation on OP request:

(?=ABC) , (?!ABC) and (?<=ABC) , (?<!ABC) are lookaheads and lookbehinds that correspond to groups before / after your expression and do not include them in the results. The one with = is positive, and the unit is with ! negative.

Here, for example, (?=(.*[az]){4}) ensures that the main expression ( .{7,10} ) has at least 4 lowercase characters. Similarly, we have one for each condition. .{7,10} ensure maximum 10 (minimum 7 - 4 lower + 1 upper + 2 digits)

The presence of such severely limited passwords (for example, usernames like this is even worse) is not recommended, as @SLaks mentions, but makes a good study of regular expressions possible :) In addition, regular expressions are not known for performance, especially gyneor.

+8
source

It might be difficult to combine all of this into a single regex expression, because you don't have an established order. You can see if php supports grouping of constructs (lookahead / lookbehind) in a regex expression, as you might be able to use them.

Here is a link to the .net regex specification. I know that you are looking at php, but it should be more or less similar in terms of what types of pattern matching you really can do.

http://msdn.microsoft.com/en-us/library/az24scfc.aspx

+1
source

All Articles