Doubts about regex challenge with multiple positive "lookaheads"

Tell us what’s happening:
Hi there, my english is kinda bad so I will try to be concise. In this challenge we are supposed to “Use lookaheads in the pwRegex to match passwords that are greater than 5 characters long, and have two consecutive digits”.

I was able to complete the challenge with a much longer regex, the one that you see bellow is the oficial solution. My main doubt is why does one needs the \w* in the second lookahead? Shouldnt it look for the double digits with just \d{2}? I removed the \w* and made some tests. The function in the second block only returns true when the double digits are at the begining of the string, what was confusing to me. But if the \w* before the d{2} is integral to the synthax shouldn’t strings like “12bana” return false in the first case? In my head the “12bana” case would need something like ((?=\w*\d{2}) | (?=\d{2}\w*))

Your code so far

let sampleWord = "bana12";
let pwRegex = /(?=\w{6})(?=\w*\d{2})/; // Solution to the Challange
let result = pwRegex.test(sampleWord);

console.log(result); // prints true for the string "bana12"

let sampleWordT1 = "bana12";
let sampleWordT2 = "12bana";
let sampleWordT3 = "123456";
let pwRegexT = /(?=\w{6})(?=\d{2})/; // Without \w* in the second look-ahead
let resultT1 = pwRegexT.test(sampleWordT1);
let resultT2 = pwRegexT.test(sampleWordT2);
let resultT3 = pwRegexT.test(sampleWordT3);

console.log(resultT1); // prints false for the string "bana12"
console.log(resultT2); // prints true for the string "12bana"
console.log(resultT3); // prints true for the string "123456"

let sampleWordB = "12bana";
let pwRegexB = /(?=\w{6})(?=\w*\d{2})/; // Solution to the Challange
let resultB = pwRegexB.test(sampleWordB);

console.log(resultB); // prints true for the string "12bana"

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36

Challenge: Positive and Negative Lookahead

Link to the challenge:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.