Regex Lookaheads (example question)

Tell us what’s happening:
Describe your issue in detail here.

Hello, everyone!

I have some questions about the example of this lesson actually. It says that:

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:

Bellow is the code that will produce this restriction:

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

It says that will look for 3-6 characters long passwords. However (and here is where my question starts), if you pass it up a 7 or more characters (with a number that is the second restriction) it will be valid as well. Which would be the same result as:

let checkPass = /(?=\w{3,})(?=\D*\d)/; //without the 6 restriction inside curly brackets.

Screen Shot 2022-04-07 at 12.06.49

Is that the expect behavior? If so, how would you limit this regex to only accepts between 3 and 6 characters?

Your browser information:

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

Challenge: Positive and Negative Lookahead

Link to the challenge:

it’s doing so because there is no anchors in there to limit the length.

This challenge has suffered a bit in trying to make it more accessible…

You need to use the below to get the desired behaviour
let checkPass = /^(?=\w{3,6})(?=\D*\d)$/;

1 Like

I’m not sure if this is the expected behavior but it is definitely possible to restrict the length to between 3 and 6 characters. First, forget about the lookaheads for a second. How would you restrict any string (can be composed of any characters) to between 3 and 6 characters? Once you have an answer for that question you are almost done. You just have to add the lookaheads back in. I’m being vague here because I don’t want to ruin the experience of figuring out for yourself. I will say that you don’t need to make any changes to the two lookaheads, you just need to add some things to get the length restriction.

Also, if you aren’t familiar with it, a great site to test regex’s is regex101. That’s what I used to solve this.

1 Like

Thanks, @ilenia!

I’ve tried your solution, but it is not working on a regular password that should pass now. Check it out:

Screen Shot 2022-04-07 at 13.26.14

Omg, regex is sooo confusing for me hahahaha

I will try this approach. Thanks @bbsmooth!

Guess I found the solution. The regex101 website is really usefull! Thanks for the tip.

Here is the regex:

checkPass = (?=^\w{3,6}\W+)(?=\D*\d);

Yeah, I know it doesn’t pass the challenge
but it’s the way to counteract this:

Are you sure this passes? It doesn’t seem to be matching for “abc123” for me.

1 Like

Yeah, it does not. Sorry about that, but i think this one will work.

checkPass = (?=^\w{3,6}$)(?=\D*\d);