regex for password

match a password

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$ %^&*-]).{8,}$
lorem ipsum gr3at@3wdsG a ab abc abcd abcde john doe johnny abcdefghijklmnopqrst

Minimum eight characters, at least one upper case English letter, one lower case English letter, one number and one special character

In this case a password may contain:

  • (?=.*?[A-Z]) : At least one upper case English letter
  • (?=.*?[a-z]) : At least one lower case English letter
  • (?=.*?[0-9]) : At least one digit
  • (?=.*?[#?!@$ %^&*-]) : At least one special character or space
  • .{8,} : Minimum eight in length

The lookahead ( (?=.*?[A-Z]) ) is used to check if after some characters if there is an occurance of an upper case letter. Similarly all the other lookaheads(lower, numbers, etc) are checked to complete the whole regex.


Cheatsheet

expr usage
/h.*llo/ the "*" matches any character(s) zero or more times... matches "hello", "heeeeeello", "hllo", "hwarwareallo"
/[abcd]/ matches any character in square brackets
/[a-z]/ matches all lowercase letters (a to z)
/[0-9]/ matches all digits
/(hello){3,}/ matches "hello" that occur atleast 3 times
/^/ matches beginning of a line
/$/ matches end of a line
/(?:hard)?work/ matches "work" or "hardwork" but is a non-capturing group
/z(?=a)/ positive lookahead... matches the "z" before the "a" in pizza but not the first "z"
iHateRegex
by geon