Why isn't this lookahead working?

Tell us what’s happening:

I don’t understand why my lookahead isn’t passing the “bana12” and “abc123” tests.

The first lookahead is checking to see if the string is at least 5 alphanumeric characters long and the second lookahead is checking to see if there are atleast 2 consectutive numbers. If both are met, it should return true, but it’s returning false. Why?

Thanks in advance.

Your code so far


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

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead/

can you look through this related post from a few days ago and see if the information shared there is enough to help?
(skip the first response by me which was incorrect)

Did you ever figure it out? I’m having trouble with that too

That solution has minor flaw. (There is an implied AND between the two lookups)

/(?=\w{5,})(?=\d{2,})/ is looking for a place where a pointer could be placed
such that there are 5 or more word characters \w immediately following
AND there are two or more digits \d also immediately following.

So 22astronaut and astron22aut would match but astronaut22 would fail to match both lookaheads. That is why test cases with numbers towards the end (less than 5 char) failed for that camper.

The second lookahead needs to be more flexible so that there can be zero or more non-digit characters proceeding the digits.

2 Likes

wow… I’ve read about 5 threads on this problem and your explanation is the first one that made me understand. I didn’t quite understand that putting two lookaheads would create a && type situation where both lookaheads needed to look for one position in the string such that they could both be fulfilled. very interesting, a lot to think about. adding the \D* such that the second lookahead is now (?=\D*\d{2,}) now means that those two consecutive numbers can be from anywhere in the string, and not just immediately following where the first lookahead could be fulfilled.

1 Like

thank you for the amazing reply.

You’re welcome :blush: