How can I make a regex to test username complexity requirements?
I'm learning about regular expressions and have one question; the answer will help me to understand regexes better.
The input is a username. This username should include at least 4 lower case chars (a-z), one upper char (A-Z) and 2 numbers. It should also have a maximum of 10 chars in total. How can I make a regular expression to test for these requirements?开发者_JAVA技巧
Use a regex with lookaheads / lookbehinds for each condition. Something like below:
^(?=(.*[a-z]){4})(?=.*[A-Z])(?=(.*\d){2}).{7,10}$
I think the regex is self explanatory, tell me if you want me to explain on each part.
Ok, explanation as per OP's request:
(?=ABC)
,(?!ABC)
and (?<=ABC)
, (?<!ABC)
- are lookaheads and lookbehinds that match groups before / after your expression and don't include them in the results. The one with =
are positive and one with !
are negative.
Here for example, (?=(.*[a-z]){4})
ensures that the main expression (.{7,10}
) has at least 4 lower case characters. Similarly, we have one for each condition. .{7,10}
ensure max 10 ( minimum 7 - 4 lower + 1 upper + 2 digits )
Having such tightly constrained passwords (whoa usernames like this are even worse) is not recommended as @SLaks mentions, but makes for some good regex learning :) Also, regexes are not known for performance, especially a ginormous one.
It might be difficult to combine all those into a single regex expression because you don't have a set order. You could look to see if php supports grouping constructs (lookahead/lookbehind) in regex expression as you might be able to use those.
Here is a link to the .net regex specification. I know you are looking at php, but it should be more or less be similiar in terms of what types of pattern matching you can actually do.
http://msdn.microsoft.com/en-us/library/az24scfc.aspx
精彩评论