Regex patterns/Validation

Password strength rules

Four independent lookaheads, each asking "is there one of these anywhere?".

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

The problem

Require a password to contain a lowercase letter, an uppercase letter, a digit, a symbol, and at least eight characters.

How it reads

startahead: must beany charrepeatskip[a-z]ahead: must beany charrepeatskip[A-Z]ahead: must beany charrepeatskip\dahead: must beany charrepeatskip[^\w\s]any charrepeatend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^(?=.*[a-z])(?=.*[A-Z…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. (?=.*[a-z])Ahead of here there must be:
  4. .*[a-z]In order:
  5. .*Any character (except a line break, unless the s flag is set), any number of times, including none, as many as possible
  6. [a-z]Any one of: "a" to "z"
  7. (?=.*[A-Z])Ahead of here there must be:
  8. .*[A-Z]In order:
  9. .*Any character (except a line break, unless the s flag is set), any number of times, including none, as many as possible
  10. [A-Z]Any one of: "A" to "Z"
  11. (?=.*\d)Ahead of here there must be:
  12. .*\dIn order:
  13. .*Any character (except a line break, unless the s flag is set), any number of times, including none, as many as possible
  14. \dA digit
  15. (?=.*[^\w\s])Ahead of here there must be:
  16. .*[^\w\s]In order:
  17. .*Any character (except a line break, unless the s flag is set), any number of times, including none, as many as possible
  18. [^\w\s]Any character except a word character (letter, digit or underscore) or whitespace
  19. .{8,}Any character (except a line break, unless the s flag is set), at least 8 times, as many as possible
  20. $The end of the text (or of a line with the m flag)

Matches

  • Sup3rSecret!
  • aB3$aB3$

Does not match

  • weakpassword
  • Sh0rt!
  • ALLUPPER1!
  • NoDigits!!

Where it bites

  • Each lookahead is zero-width: it checks from the start and gives the position back, which is why four of them can stack without the pattern needing the characters in any particular order.
  • The .{8,} at the end is what actually consumes the password — remove it and the pattern matches an empty string.
  • Composition rules like these are no longer recommended as the primary defence; length and a breach check do more. Encode policy where you can explain it, not only in a regex.

More validation patterns