I am using Regex to match passwords that are greater than 5 characters long and have two consecutive digits in JavaScript.
I tried it two different methods using lookahead, the first method returns false, whereas the second one returns true.
Here is the code:
let sampleWord = "abc123";
let pwRegex = /(?=\w{5,})(?=\d{2,})/; //returns false
let result = pwRegex.test(sampleWord);
console.log(result);
let sampleWord = "abc123";
let pwRegex = /(?=\w{5,})(?=\D*\d{2,})/; //returns true
let result = pwRegex.test(sampleWord);
console.log(result);
The only difference is that the second one also has \D*
. As far as I know, it checks for non-numeric values occurring 0 or more times. But why is it required in this case?
P.S. This is a part of a challenge at FreeCodeCamp.org for learning Regular Expressions