Regular Expressions Explained: A Beginner's Guide to Regex

Regular expressions have a reputation for looking like line noise — a dense string of symbols that's intimidating to read, let alone write. But the underlying concept is genuinely simple once broken down piece by piece: a regex is just a pattern-matching language for text.

What problem regex actually solves

Searching for an exact word is easy with a normal text search. Searching for "any valid email address," "any phone number regardless of formatting," or "any line starting with a number" requires describing a pattern rather than an exact string — that's precisely what regex is built for.

The core building blocks

  • Literal characters: cat matches exactly the text "cat".
  • . (dot): Matches any single character. c.t matches "cat", "cot", "c9t".
  • * (asterisk): Matches the previous character zero or more times. ca*t matches "ct", "cat", "caaat".
  • + (plus): Matches the previous character one or more times (at least one, unlike *).
  • ? (question mark): Makes the previous character optional (zero or one occurrence).
  • \d: Matches any digit (0-9). \w: matches any word character (letters, digits, underscore).
  • [ ] (brackets): Matches any one character inside the brackets. [aeiou] matches any single vowel.
  • ^ and $: Anchor a match to the start (^) or end ($) of a line.

A worked example

A simplified pattern for matching a US phone number like 555-123-4567:

\d{3}-\d{3}-\d{4}

Reading this piece by piece: \d{3} means "exactly 3 digits," followed by a literal hyphen, then another 3 digits, another hyphen, then 4 digits. Once you can read patterns piece by piece like this, regex stops looking like noise and starts looking like a sentence.

Greedy vs. lazy matching — a common gotcha

By default, * and + are "greedy" — they match as much text as possible. Given the text <b>bold</b>, the pattern <.*> greedily matches the entire string from the first < to the last >, rather than stopping at the first closing tag — often not what a beginner expects. Adding a ? after the quantifier (<.*?>) makes it "lazy," matching as little as possible instead, which usually gives the intended result for cases like this.

Where regex is genuinely useful day to day

Validating form input (emails, phone numbers, postal codes), search-and-replace across a large document or codebase, extracting specific data from log files, and filtering lines in a text file are all common, practical uses — not just something confined to advanced programming.

Our free Regex Tester & Visualizer shows live match highlighting as you type your pattern, plus a plain-English breakdown of what each part of your regex actually does.