Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

When using lookaheads, why wouldn't + work instead of .*

In the "Validating a Password" lesson of the Regular Expression course, the expected password must contain a lowercase letter, an uppercase letter, and a number. https://teamtreehouse.com/library/validating-a-password .

Why would this regex work:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/

but this wouldn't:

/^(?=\d+)(?=[a-z]+)(?=[A-Z]+).*$/

Why?

1 Answer

Steven Parker
Steven Parker
243,266 Points

You forgot to provide a link to the course page, so I'm not sure what the exercise criteria are. But these specify rather different requirements. Just looking at the meanings of one part, for example:

  • .*[a-z] :point_left: accept any number of any kind of characters followed by a lower-case letter
  • [a-z]+ :point_left: accept only one or more lower-case letters

This is the lesson: https://teamtreehouse.com/library/validating-a-password .

Thanks for the response, Steven Parker . I still don't understand why my solution doesn't pass the password validation though.

Steven Parker
Steven Parker
243,266 Points

As I said, the first pattern matches if the character (lower case letter in this example) is found after any number of other characters, so it can be at any position. But the second pattern matches only if the very first character (and any number of others) matches.

Since the first character cannot be lower case and upper case and a number, the second regex rejects everything.