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/

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.

If there are 3 consecutive digits, then there are definitely 2 consecutive digits (a subset of the 3 consecutive digits).

Exactly! When using two lookaheads in this manner, you can think about them as checking independently.

1 Like

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.