This works, but why must it be that way?

Tell us what’s happening:
Hi, the answer below works, but I am curious to know why it needs the ‘\w*’ in the second lookahead.

Without the above, the code does not pass. I would think that without it, the code would still lookahead to find 2 digits (\d) and pass the regex, but it fails for the string, bana12, for instance.

Your code so far


let sampleWord = "astronaut";
let pwRegex = /(?=\w{6,})(?=\w*\d{2})/; // Change this line
let result = pwRegex.test(sampleWord);

Your browser information:

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

Challenge: Positive and Negative Lookahead

Link to the challenge:

I think the reason you need it is because this /(?=\d{2})/ looks for 2 consecutive digits that are not preceded by anything, whereas /(?=\w*\d{2})/ this looks for two consecutive digits preceded by any number of alphanumerical characters.

The whole line /(?=\w{6,})(?=\w*\d{2})/ is basically two separate conditions that will be checked independently of each other.

Someone asked about this challenge some time ago and I gave a detailed walkthrough here: regExp - use of \D* before \d{2}? - #2 by gaac510

1 Like

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