rostej
rostej

Reputation: 69

What does this RegExp pattern /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/ mean in Javascript?

This regex

/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/ 

pattern is intended to match a valid password.

I've searched the answer on regexper.com, here is the link.

I know the meaning of the contents in each parenthesis, but I don't know why here are there parentheses and how they work together..

Upvotes: 2

Views: 10056

Answers (2)

wp78de
wp78de

Reputation: 18950

The pattern (?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,} asserts

  • 6 or more characters
  • a digit
  • a lower-case letter
  • an upper-case letter

That's it.

Explanation of the moving parts:

  • (?=.*\d) checks if a digit exists using a positive lookahead.
  • (?=.*[a-z]) checks in the same fashing to see if a lowercase letter exists.
  • (?=.*[A-Z]) .. and an uppercase letter exists as well.
  • .{6,} The 6+ quantifier is obvious.

The beauty of using a lookahead here is it makes it easy to (spot and) maintain the password rules.

Upvotes: 4

CrayonViolent
CrayonViolent

Reputation: 32532

(?=.*\d) This is a positive lookahead to see if a digit exists

(?=.*[a-z]) This is a positive lookahead to see if a lowercase letter exists

(?=.*[A-Z]) This is a positive lookahead to see if an uppercase letter exists

.{6,} This matches for 6 or more of any character

So overall, it expects a string of 6 or more characters that contains at least one number, one lowercase letter, and one uppercase letter.

Upvotes: 1

Related Questions