I don’t really understand lookarounds with regular expressions. I’ll just give you guys an example - it says to “Use lookaheads in the pwRegex to match passwords that are greater than 5 characters long, and have two consecutive digits.”
I don’t understand what the difference between /(?=\w{5,})(?=\D+\d\d+)/ and /\w{5,}(?=\D+\d\d+)/ is. Can someone help me here?
The ?= means that captured match must be followed by whatever is within the parentheses, but that part isn’t captured.
Hope this example helps you:
let test1 = "abcdeF22";
//This get more than one coincidence
//Exactly nothing followed by (?=\w{5,}) and followed by (?=\D+\d\d+)
//Every where At least 5 char + one or more char +, one digit +, one or more digit
let regex1 = /(?=\w{5,})(?=\D+\d\d+)/gi;
let test2 = "abcdeF22";
//This get exactly coincidence
//At least 5 char \w{5,} that must be followed by (?=\D+\d\d+)
// At least 5 char Followed by one or more char +, one digit +, one or more digit
let regex2 = /\w{5,}(?=\D+\d\d+)/gi;
console.log(test1.match(regex1), regex1.test(test1))
console.log(test2.match(regex2), regex2.test(test2))
the 2 look ahead are run from the start of the string. You can think of it as 2 different regular expressions, both must be true for the result to be true. The second one, uses the position.
Explanation
/(?=\w{5,})(?=\D+\d\d+)/
string contains 5 or more symbols (mostly [a-zA-Z0-9]),
string contains 1+ non digit followed by 2+ digits. You could also write \d{2,}
Mind the word “contain”. Both look ups look at the whole string, starting from the beginning. If this one passes"hel12lo", anything surrounding it will as well.
/\w{5,}(?=\D+\d\d+)/
In this case, the look up starts from the 5th character, as far as I can tell. So I’d read it as: 5 or more symbols, then - after the 5th - 1 or more non digit, and then 2 or more digits.
So in this case, the string "hel12lo" Won’t pass. You can play around