Positive and Negative Lookahead - Matching All-Digit Password

Tell us what’s happening:
When I run this code:


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

I get the following error: Your regex should not match the string 12345

My regex design is:

  • (?=\w{5,}) - Lookahead for 5 or more alphanumeric characters (I know it’s supposed to be greater than five).
  • (?=\D*\d{2}\D*) - Match any number of non-digits, followed by exactly 2 digits, followed by any number of non-digits.

I don’t understand why this would match 12345.

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0

Challenge: Positive and Negative Lookahead

Link to the challenge:

12 is two digits with before 0 non digits and after 0 non digits (0 is also any number)

but the reason why 12345 should not pass it is because it is not longer than 5 characters

Hello there,

I could be misunderstanding it myself, but I believe the issue is the first lookahead matches 12345, and the second lookahead matches 12.

This happens, because of the way lookaheads interact with one another. In that, they do not interact with one another. It is the same reason, you can switch the order of the lookaheads, and the behaviour will be the same.

Hope this helps

2 Likes

OK, that makes sense.

Honestly I was originally going to make this question “How do capture groups interact”. I guess there’s no way to actually make it look for two consecutive digits anywhere in the string without making it match an all-digit string.

2 Likes

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