How to Test and Debug Regular Expressions
Regular expressions are powerful and famously hard to read. The fastest way to get one right is to build it incrementally and test it against real text as you go. Here's a practical approach.
Start with the anchors and literals
Write the parts you're sure about first — literal characters and anchors:
^matches the start of the string,$the end.- Most characters match themselves; escape special ones with
\(e.g.\.for a literal dot).
Then add the variable parts one piece at a time, checking each addition against your test text so you can see exactly where a change breaks.
Learn the core building blocks
- Character classes —
\d(digit),\w(word char),\s(whitespace), and[a-z](a custom set). - Quantifiers —
*(zero or more),+(one or more),?(optional),{2,4}(a range). - Groups —
( )captures a match for later use;(?: )groups without capturing. - Alternation —
cat|dogmatches either.
Use flags deliberately
Flags change how the whole pattern behaves:
g— find all matches, not just the first.i— case-insensitive.m—^and$match at each line break.
A pattern that "doesn't work" often just needs the g or i flag.
Read the capture groups
When your pattern has ( ) groups, each match exposes the captured sub-strings. Testing against real input and inspecting those groups is the quickest way to confirm you're capturing the right pieces — and to catch greedy quantifiers grabbing too much (switch .* to the lazy .*? when that happens).
Related
Part of The Complete Guide to Regular Expressions. See also Character Classes, Quantifiers & Anchors and Groups, Backreferences & Lookarounds.
Try it
Type a pattern and paste your test text to see matches highlighted live, with capture groups listed as you type — all in your browser, nothing uploaded.