Regular Expressions (RegEx) are the dark magic of computer science. Extremely powerful, but arguably the least readable syntax ever invented. However, you don't need to be a wizard to use them. You just need a few solid spells in your book.

Here are the 5 patterns that solve 90% of validation problems I encounter.

1. The "Good Enough" Email Validator

Validating emails perfectly is actually impossible with regex (the RFC spec is pages long). But for a login form, you just need to catch typos.

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

Breakdown:

  • `^` : Start of line.
  • `[a-zA-Z0-9._%+-]+` : One or more allowed characters for the username.
  • `@` : The literal @ symbol.
  • `[a-zA-Z0-9.-]+` : The domain name.
  • `\.` : A literal dot.
  • `[a-zA-Z]{2,}` : The extension (TLD) must be at least 2 letters (e.g., .com, .io).

2. ISO 8601 Dates (YYYY-MM-DD)

Essential for validating API date inputs.

^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

Why it works: It's strict. It forces the month to be 01-12 and the day to be 01-31. It prevents inputs like `2024-99-99`.

3. Simple Password Strength

Enforce: At least 8 chars, 1 uppercase, 1 lowercase, 1 number.

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$

The Magic of Lookaheads `(?=)`: These verify a condition without "consuming" characters. It checks for a lower, then upper, then digit, independently.

4. Extracting Domain from URL

Useful for analytics or cleaning data lists.

(?:https?:\/\/)?(?:www\.)?([^:\/\n]+)

This ignores the protocol (`http://`) and `www.`, capturing just `google.com` or `toolbit.dev`.

5. Matching Empty Lines

Great for cleaning up text files or code.

^\s*$

This matches any line that is either completely empty or contains only whitespace (so spaces and tabs don't trick you).

Bonus: Combining Patterns

Real-world validation often requires multiple checks. Instead of writing one monstrous regex that handles every edge case, chain simple patterns together:

// Instead of one mega-regex for "valid username":
const isValidLength = /^.{3,20}$/.test(input);
const hasValidChars = /^[a-zA-Z0-9_]+$/.test(input);
const startsWithLetter = /^[a-zA-Z]/.test(input);

const isValid = isValidLength && hasValidChars && startsWithLetter;

Each rule is readable, testable, and produces a specific error message. This is far better than a single pattern that either matches or doesn't, with no indication of why it failed.

Testing is Key

Never deploy a regex without testing it against edge cases (like empty strings or huge inputs). Use a real-time tester to visualize exactly what your pattern is matching.

Want to test these patterns live? Paste them into our RegEx Tester and see matches highlighted in real-time with detailed explanations.