Explain this regex to me like I’m five
What does this do? I copied it from a Stack Overflow answer and I’m scared of it.
^(?=.*[A-Z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,}$It’s a password rule, and it’s less scary than it looks. Read it as three bouncers standing at a door:
(?=.*[A-Z])— Bouncer 1 peeks down the whole line and asks “is there at least one capital letter somewhere?” He doesn’t move, he just checks.(?=.*\d)— Bouncer 2 does the same for a digit.[A-Za-z\d!@#$%^&*]{8,}— Bouncer 3 actually walks the line: every character must be a letter, digit or one of!@#$%^&*, and there must be at least 8 of them.
^ and $ mean “from the very start to the very end” — no sneaking extra characters in.
So: 8+ characters, only from that set, with at least one uppercase and one digit.
One gotcha: it doesn’t allow spaces or characters like - or _. If a user picks correct-horse-Battery9, it fails because of the hyphens. That’s usually a bug, not a feature.
How do I allow hyphens and underscores?
Add them to the third bouncer’s list. Put the hyphen at the end so it isn’t read as a range:
^(?=.*[A-Z])(?=.*\d)[A-Za-z\d!@#$%^&*_-]{8,}$
Honestly, though: if you control the backend, consider dropping the character allow-list entirely and only enforcing length + the two lookaheads. Longer passphrases beat symbol rules.
Comments (1)
:)
Sign in to comment.