Positive and Negative Lookahead_2

Tell us what’s happening:
I can’t pass the tests with numbers at the end of the password. I figured (?=\d{2}) would work since that covers only two numbers at the end, but it doesn’t, and I don’t know why. \d+ won’t work because that covers one or more numbers, and we only want two. Thanks.

Your code so far


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

Your browser information:

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

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

Regex works slightly different from human brain, (?=\d{2}) doesn’t mean go find 2 digits, what regex is doing instead, it checks from the first character to the last:

CHAR 1: Is it \d? No -> No Match!

Hope this would help :slight_smile:

So, within each grouping regex starts at the beginning of “astronaut?” In the second grouping, (?=\d{2}), regex starts over again, so you’d have to have a .* in front to compensate for the first grouping of characters (?=\w{6,})? Thanks!

Look-ahead doesn’t really move, it stays where it stopped (in your case - before the first character) and peeks string from that position. It never really matches or captures anything, just tells true or false