Positive and Negative Lookahead0

Tell us what’s happening:
These two test cases are failing. Please do help me and Thanks in advance.
Your regex should match "bana12"

Your regex should match "abc123"

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 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0.

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

The key thing to understand when working with lookaheads is backtracking. Hopefully this will help:
“Lookarounds ensure a position and when you add multiple lookarounds the assertion must be true for all of them for this specific position. Roughly speaking, for lookaheads - they require the text immediately to the right of that position to match both patterns at the same time”

Your regexp will match “ba22banana”, because both lookaheads get matches: first one matches “22ban” and second matches “22”.

Your regexp WILL NOT match “bana12” because second lookahead matches “12” and the first one only matches “12” before the string ends, which means that it’s only 2 symbols instead of 5, so as a result the test fails.

Another example : “ba2244” will fail, because “2244” is the first match and the first lookaround runs out of characters when trying to match from the same position.

BUT, “b22abcd44” will match and will return true, because it matches only the first occurrence(since we are not using the g flag only the first match matters) of two digits in a row, which is ‘22’ and the (?=\w{5,}) lookahead matches ‘22abc’.

So you see, both have to start from the same position. The condition in your second lookahead has to start matching more things and can’t include just the digits alone in order for this to work the way the requirements demand it to.