Regular Expressions: Positive and Negative Lookahead austin

Tell us what’s happening:
I’m looking at the example given in the Positive and Negative Lookahead Lesson. Here it is:
A more practical use of lookaheads is to check two or more patterns in one string. Here is a (naively) simple password checker that looks for between 3 and 6 characters and at least one number:

let password = “abc123”;
let checkPass = /(?=\w{3,6})(?=\D*\d)/;
checkPass.test(password); // Returns true

However, if password = “abcd123” it still return as true, even though the password has more than 6 characters. Why is that? Shouldn’t this return as false if there are more than 6 characters?

Also, I don’t understand how the lookahead works when there is nothing in front of the (?=…) as given in this example. The other examples have something in front, as with q(?=u). How can you have a lookahead with nothing in front of the lookahead?

Your code so far

Your browser information:

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

Challenge: Positive and Negative Lookahead

Link to the challenge:

I’ll translate this regex to English and see if you can spot the problem:

  1. Anywhere ahead of me there must be three to six _alphanumeric characters
  2. Anywhere ahead of me there must be a digit possibly preceded by any number of non-digit characters

DISCLAIMER: “Anywhere” is somewhat incorrect technically, but still OK to understand the behaviour.

Ok thank you that does help! It seems that this regex just checks to see if there are 3-6 alphanumeric characters in the string (“ahead of me”), but the string can still be more than 6 characters.

Exactly! There is no way lookaheads can test the maximum boundary. In order for this regex to work you need to unwrap the first lookahead and introduce boundaries ^...$:

const re = /^(?=.*\d)\w{3,6}$/;
re.test('abc123'); // true
re.test('abcd123'); // false
1 Like