Regular Expression Basics for Beginners
A practical introduction to regex: literals, metacharacters, quantifiers, groups, flags, and how to test a pattern safely.
A regular expression (regex) is a compact pattern for matching text. Once you know a small vocabulary of symbols, you can find, validate, and replace text far more flexibly than with plain search.
Literal characters
Most characters match themselves. The pattern cat matches the letters c, a, t in that order, anywhere in the text.
Metacharacters and classes
A few symbols carry special meaning, and short codes stand for character groups:
- . matches any single character (except a newline by default).
- \d a digit (0-9), \w a word character (letter, digit, or underscore), \s whitespace.
- [abc] any one of a, b, or c; [^abc] any character except those.
- ^ start of a line and $ end of a line.
- \b a word boundary.
Quantifiers
- * zero or more, + one or more, ? zero or one.
- {3} exactly three, {2,5} between two and five.
- Add ? to make a quantifier lazy (match as few as possible), e.g. +?.
Groups and capture
Parentheses group part of a pattern and 'capture' what they match so you can reuse it. In a replacement, $1 refers to the first captured group, $2 to the second, and $<name> to a named group.
Pattern: (\d{4})-(\d{2})-(\d{2})
Matches: 2026-10-05
Replace: $3/$2/$1 -> 05/10/2026Flags
- g — find all matches, not just the first.
- i — case-insensitive.
- m — let ^ and $ match each line, not just the whole text.
- s — let . also match newlines.
- u — full Unicode mode.
A caution: catastrophic backtracking
Some patterns — especially nested quantifiers like (a+)+ — can take exponential time on unlucky input and freeze the page. This is known as ReDoS. When testing unfamiliar patterns, use a tool that caps input size and warns about these shapes.

