I want a regular expression to check that:
A password contains at least eight characters, including at least one number and includes both lower and uppercase letter
You may use this regex with multiple lookahead assertions (conditions):
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$
This regex will enforce these rules:
(?=.*?[A-Z])
(?=.*?[a-z])
(?=.*?[0-9])
(?=.*?[#?!@$%^&*-])
.{8,}
(with the anchors)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$
Link check online https://regex101.com/r/mqGurh/1
Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...
But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords:
Anything with less than eight characters OR anything with no numbers OR anything with no uppercase OR or anything with no lowercase OR anything with no special characters.
So:
^(.{0,7}|[^0-9]*|[^A-Z]*|[^a-z]*|[a-zA-Z0-9]*)$
If anything matches that, then it's an invalid password.
Pattern to match at least 1 upper case character, 1 digit and any special characters and the length between 8 to 63.
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d\\W]{8,63}$"
This pattern was used for JAVA programming.
Try this:
^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$
This regular expression works for me perfectly.
function myFunction() {
var str = "c1TTTTaTTT@";
var patt = new RegExp("^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$");
var res = patt.test(str);
console.log("Is regular matches:", res);
}
Not directly answering the question, but does it really have to be a regex?
I used to do lots of Perl, and got used to solving problems with regexes. However, when they get more complicated with all the look-aheads and other quirks, you need to write dozens of unit tests to kill all those little bugs.
Furthermore, a regex is typically a few times slower than an imperative or a functional solution.
For example, the following (not very FP) Scala function solves the original question about three times faster than the regex of the most popular answer. What it does is also so clear that you don't need a unit test at all:
def validatePassword(password: String): Boolean = {
if (password.length < 8)
return false
var lower = false
var upper = false
var numbers = false
var special = false
password.foreach { c =>
if (c.isDigit) numbers = true
else if (c.isLower) lower = true
else if (c.isUpper) upper = true
else special = true
}
lower && upper && numbers && special
}