Regular Expressions: A Beginner's Guide
September 8, 20267 min readLearn regex from scratch — the core building blocks, flags, capture groups, and the one performance trap to avoid.
Regular expressions (“regex”) are a tiny language for describing patterns in text. They look cryptic — ^\d{3}-\d{4}$ — but the core ideas are learnable in a few minutes, and once you have them, you can search, validate, and transform text far faster than by hand. This guide covers the essentials with examples you can try in the Regex Tester.
The building blocks
A regex is read left to right, matching literal characters unless a character is “special.” The most useful pieces:
.— any single character.\d— any digit;\w— a word character (letter, digit, underscore);\s— whitespace.*— zero or more of the previous item;+— one or more;?— zero or one (optional).{3}— exactly three;{2,4}— between two and four.[abc]— any one of a, b, or c;[a-z]— any lowercase letter.^— start of the string;$— end of the string.|— or; parentheses( )group things together and capture them.
Reading a real pattern
Take ^\d{3}-\d{4}$. Piece by piece: ^ anchor to the start, \d{3} exactly three digits, - a literal hyphen, \d{4} four more digits, $ end of string. So it matches 123-4567 but not 12-4567 or 123-4567 ext. Anchoring with ^ and $ is what makes it validate the whole string rather than just find a match inside it.
Flags change how matching works
- g (global) — find all matches, not just the first.
- i (ignore case) — treat
Aandaas the same. - m (multiline) — make
^and$match at each line break.
The Regex Tester lets you toggle these and see the matches update live, which is the fastest way to learn what each one does.
Capture groups: pulling data out
Parentheses don’t just group — they capture. In (\d{4})-(\d{2})-(\d{2}) matched against 2026-09-08, group 1 is the year, group 2 the month, group 3 the day. That’s how you extract structured pieces (dates, prices, IDs) out of messy text.
The one trap to avoid: catastrophic backtracking
Certain patterns — often nested quantifiers like (a+)+ — can make the regex engine try an explosion of combinations on some inputs, hanging the browser or server. This is called catastrophic backtracking (a form of ReDoS). If a regex is mysteriously slow, simplify the nesting or make quantifiers more specific. It’s a good reason to test patterns against realistic input before shipping them.
Practical tips
- Build patterns incrementally, testing after each addition, rather than all at once.
- Anchor with
^…$when validating, and leave anchors off when searching within text. - Regex is great for well-structured text — but don’t try to parse full HTML or JSON with it; use a real parser (like our JSON Validator).