Already solved, need clarification

Tell us what’s happening:

Your code so far


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

Your browser information:

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

Challenge: Positive and Negative Lookahead

Link to the challenge:

I was doing this problem and got pretty close to getting it right the first time (had to use hints) but i looked at the solution provided on the forums under the hint page and im extremely confused why it decides to use a {5} over a {5,} when specifying the number of characters required. In a previous lesson, i thought I had understood that {5} would match ONLY substrings which contain 5 characters, however this is applied when you need 5 characters or more in this problem and it seems to work fine? Did I misunderstand this and the comma is unneccessary?

The reason that it works is because the pattern does not have to match the whole string in order to “match”. If the string (sampleWord) contains the pattern, it will find a match. If the person writing that solution had used the end-of-string character ($) it would be a different story, because that would require the whole string to match the pattern.

Keep in mind that the solutions included in the Guide are not necessarily the “best” solutions. They are examples of ways you could solve the problem.

1 Like

Ahhhhhh makes so much sense! Thank you!!

I’m glad I could help. Congratulations on solving the challenge. Regular expressions can be rough.

Happy coding!

1 Like