0

This is the javascript regular expression I'm confused about. I know that (?=) is the positive lookahead, but is there suppose to have a main expression before that?

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/

The answer says it matches a password which is:

at least one number, one lowercase and one uppercase letter and at least 8 characters that are letters, numbers or the underscore

But I don't see why. Can somebody explain a little?

Jiawei An
  • 13
  • 2
  • You need to read about regex, for now d is for digits, [a-z] is for lower case character, [A-Z] is for upper case characters, w is for word.. It will take you about an half an hour to understand atleast basics of regex if you're willing to spend your time on it. – Nikhil Chavan Feb 23 '17 at 07:47
  • 1
    Read [this](https://regex101.com/r/bRdYk9/1) for a comprehensive explanation of that regex ... keep that page in mind for other regex mysteries you stumble on – Jaromanda X Feb 23 '17 at 07:47
  • Why would a positive lookahead need another expression before it? – JJJ Feb 23 '17 at 07:47

1 Answers1

2

Let's break it down:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/

^                     // Match the start of the string
(?=.*\d)              // Make sure the string contains at least one digit
(?=.*[a-z])           // Make sure the string contains at least one lowercase letter
(?=.*[A-Z])           // Make sure the string contains at least one uppercase letter
\w{8,}                // Match at least eight word characters (alphanumeric or underscore)
$                     // Match the end of the string

(?=.*PATTERN) is a common way to ensure that a match string contains PATTERN.

It works because .* matches anything (except newline characters); the lookahead literally means "This regex should only match if you find PATTERN after something."

gyre
  • 14,437
  • 1
  • 32
  • 46