Regular expressions by example

A regular expression describes the shape of some text. Instead of comparing character by character, you write a pattern and the engine tells you whether a string matches. It's the fastest tool to validate input, pull out a fragment, or search-and-replace in an editor.

The building blocks

A handful of symbols cover most day-to-day needs:

  • \d a digit, \w a letter, digit or underscore, \s whitespace
  • + one or more, * zero or more, ? optional
  • ^ start of string, $ end of string
  • [a-z] a range, (…) a group you can reuse

💡 Anecdote - Developer Jamie Zawinski nails the trap: "Some people, faced with a problem, think 'I'll use regular expressions.' Now they have two problems."

Three real cases

A US ZIP code: ^\d{5}$ - exactly five digits, nothing before or after. An ISO date: ^\d{4}-\d{2}-\d{2}$. An email, the pragmatic version: ^[^@\s]+@[^@\s]+\.[a-z]{2,}$ - some text, an at sign, a domain, a dot, an extension. Don't chase the perfect email regex: the only reliable proof is sending a confirmation message.

Test before shipping to production

A regex is hard to read and even harder to debug by eye. Build it from concrete examples, add edge cases one at a time, and check what matches and what shouldn't. Our regex tester highlights matches live, entirely in your browser - your test data never leaves your machine

🤓 Did you know? The grep command is named after an ed editor command: g/re/p (global / regular expression / print) printed lines matching a pattern. "To grep" has since become a verb among developers.