Question about lookahead

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.


Positive and Negative Lookaheadx

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


Why isn't this lookahead working?

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)


Positive and Negative Lookahead - \D*

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.




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.