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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With