Regular Expressions - Positive and Negative Lookahead

Tell us what’s happening:
Describe your issue in detail here.

Why do we have to add the none-digit \D* first and add additionally \d?
It can’t be done just \d to indicate at least one number?

Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Regular Expressions - Positive and Negative Lookahead

Link to the challenge:

Well for one, there should be at least 2 consecutive digits according to the instructions.

if at least 2 consecutive digits are required, i was thinking of using \d\d+ or \d{2,}. I don’t understand the usage of \D in this context as it means none-digit

Did someone tell you that you have to use \D in your regular expression? You don’t have to use that specifically, but you do need to make sure you can catch double digits appearing anywhere in the string.

Remember when using two lookaheads, both must match. One thing that is not mentioned is lookaheads are zero-width assertions. These means that when the lookahead patterns are matched, the regex index stays at the same place where it has been before. In your current regex, when the first lookahead (?=\w{5,}) is matched, the index still is located at the beginning and so the next lookahead starts searching at the beginning of what was matched. With your second lookahead (?=\d{2}) you are trying to find two digits at the start of what was matched in the previous lookahead. Prefixing the \D* allows the digits to be anywhere after 0 or more characters.

FYI - the (?=\w{5,}) will only match greater than 4 word characters instead of greater than 5 word characters.

1 Like

Much appreciate your explanation!

But what if we take first lookahead from this discussion (?=\w{5,}) and change sampleWord = “astronaut” to smth like “…astronaut” (instead of dots we can use any characters that are not included in /w character class)
e.g. :

let sampleWord = "..........astronaut";
let pwRegex = /(?=\w{5,})/; 
let result = pwRegex.test(sampleWord);

So the value of ‘result’ variable will be true, though \w character class includes only [A-Za-z0-9_]
In context of explanation above, how could this be possible?
I really got stuck, because explanation is clear and correct, but contradictory at the same time

This evaluates to true because \w{5,} is going to see astronaut as a match. Nothing is actually captured, which is why if you wrote:

let sampleWord = "..........astronaut";
let pwRegex = /(?=\w{5,})/; 
let result = sampleWord.match(pwRegex); // [""]

you would get an array with an empty string.

Having a single positive lookahead is not the same as two consecutive positive lookaheads, so I am not sure what you are confused about.