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.
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
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.