Positive Lookahead Help

I’ll keep this succinct:

We just need to edit the second line to match passwords that are greater than 5 characters long, and have two consecutive digits.

The correct line of code is /(?=\w{6,})(?=\w*\d{2})/;

I’m wondering why this doesn’t work: /(?=\w{6,})(?=\d{2})/;

The code in the first set of parentheses satisfies the first rule (must be 5+ characters long) and the code in the second set satisfies the second set (must have two consecutive digits).

The \w* just means it has 0+ characters before it but that doesn’t mean anything. You could also put that after the \d{2} but you don’t have to.

I would somewhat understand it if the numbers have to be at the end but they don’t.

Any help would be appreciated.

Your code so far

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


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:90.0) Gecko/20100101 Firefox/90.0

Challenge: Positive and Negative Lookahead

Link to the challenge:

so the important thing to know about lookahead/lookbehinds is that they do not consume the string unlike the usual regex.

Usually say you got a regex that’s something like /\d\w/ and a string like “7w”, we have a match because \d consumes the “7” and the regex tries to match the character after, “w” with \w.

But with lookaheads/lookbehinds, you do not consume the match found at all. In the regex you gave, and a test password of “abcdefc1234”. (?=\w{6,}) finds a match, starting from the beginning of the string and sees that the string indeed has more than 5 characters at the beginning. And goes back to the beginning of the string again for the second part of the regex: (?=\d{2}) which would find no match because the string does not start with digits.

Regex can be a bit hard, it’s easier to visualize with tools such as https://regex101.com/

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.