Question about lookahead

In this lesson of regular expression I am asked to match passwords that are greater than 5 characters long and have two consecutive digits. I solved the challenge as followed:

let sampleWord = "astronaut";
let pwRegex = /(?=\w{5})(?=\D*\d{2})/;
let result = pwRegex.test(sampleWord);

My question is, why do we need this piece of code \D*? Why do I need to check for non-digit characters before doing this \d{2}? The challenge is just asking me to check that the password has at least 2 digits.

you didnā€™t post a link to the challenge, so I have to use my (bad) memory for this:

I believe the challenge said the digits have to be at the end ? So not at the beginningā€¦

I believe I did, but just in case this is the challenge https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead/

thanks, I missed your first linkā€¦
The challenge doesnā€™t actually say ā€˜at leastā€™. It just says has 2 consecutive digits. Therefore, it should not have 3
or more consecutive digits, and it should not have 1 digit or less either.

so that means the other characters found in the lookahead have to be non-digits (\D)

2 Likes

Well, even though the challenge doesnā€™t say ā€œat least 2ā€ digits, it passes the test even with 3 consecutive digits (and more probably), so I thought the requirement was minimum 2 digits.

However your answer clarified something for me, basically I was looking at the whole picture, meaning this (?=...)(?=....) was just one lookahead in my mind, but instead we have 2 and each one is checking for something different.

Thanks.

yes I see what you mean. I think they must have meant 2 consecutive digits even if they occur within a grouping of a greater number.