I have built a regular expression for password policy match, but it is not working as expected
/((?=. \\d)(?=. [az])(?=. [AZ])(?=. [@#\\$%!])(?!(.)*\\1{2,}).{6,20})/
Password must satisfy below rules
-> must have 1 digit
-> must have 1 upper case letter
-> must have 1 lower case letter
-> must have 1 special character from given list
-> minimum 6 character long
-> maximum 20 character long
-> Not more than 2 identical characters`
So it matches
aDm!n1, Adw1n@
but it must not match below aaaD!n1, teSt@111
I have searched for this regular expression and found "(?!(.)*\\1{2,})" is not working properly
I am not getting why it is not working even though it has lookahead negative assertion.
Thanks in advance
You must need to provide start and end anchors.
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#\$%\!])(?!.*(.).*\1.*\1).{6,20}$
To match the strings which isn't contain more than two duplicate characters, you need to use a negative lookahead like (?!.*(.).*\\1.*\\1)
which asserts that the string we are going to match wouldn't contain not more than two duplicate characters.
(?!)
Negative lookahead which checks if there isn't .*
Any character zero or more times. (.)
A single character was captured. .*
Any character zero or more times. \\1
Reference to the group index 1. That is, it refers to the character which are already captured by group 1. .*
Any character zero or more times. \\1
Back-referencing to the character which was present inside the group index 1. Code:
> var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#\$%\!])(?!.*(.).*\1.*\1).{6,20}$/;
undefined
> re.test('aDm!n1')
true
> re.test('Adw1n@')
true
> re.test('tetSt@11')
false
(?:(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#\$%!])(?!.*(.).*\1.*\1).{6,20})
You need this.See demo.
http://regex101.com/r/hQ9xT1/22
Your regex was failing cos
(?!(.)*\\1{2,})
will not work as it find consecutive repeated characters and not any character which is three times or more.So use (?!.*(.).*\\1.*\\1)
.
var re = /^(?:(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#\$%!])(?!.*(.).*\1.*\1).{6,20})$/gm;
var str = 'aaaD!n1\nteSt@111\naDm!n1\nAdw1n@';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.