THE HONEST ADVICE FIRST
Do not validate email with a regex. Use a library, or just send a confirmation
email - that is the only real test. Everything below is for matching, not for
deciding whether something is legal.
ROUGH-AND-READY (good enough for forms)
email-ish ^[^@\s]+@[^@\s]+\.[^@\s]+$
url ^https?://[^\s/$.?#].[^\s]*$
ipv4 ^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$
hex colour ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
uuid v4 ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$
slug ^[a-z0-9]+(?:-[a-z0-9]+)*$
iso date ^\d{4}-\d{2}-\d{2}$
USEFUL CONSTRUCTS
(?i) case-insensitive from here
(?:...) group WITHOUT capturing (faster, cleaner)
(?=...) lookahead - must be followed by
(?!...) negative lookahead - must NOT be followed by
(?<=...) lookbehind - must be preceded by
\b word boundary - the fix for "cat" matching "concatenate"
*? +? lazy quantifiers - match as little as possible
THE TWO BUGS EVERYONE HITS
1. Forgetting \b. /hat/ matches "that". /\bhat\b/ does not.
2. Greedy quantifiers. <.*> eats the whole line; <.*?> stops at the first >.
PASSWORD "STRENGTH" (lookaheads, all must pass)
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{12,}$
...though length matters far more than character classes. Prefer a minimum of
12-16 and a check against known-breached lists.