Regex Testing 101: How to Write and Debug Regular Expressions
Regular expressions are powerful but famously hard to read and debug. The key is testing incrementally — never write a full regex and hope it works.
Start With a Small Pattern
Begin with the simplest version of what you want to match. If you need to extract email addresses, start by matching the @ symbol. Then add the local part, then the domain. Test each addition before moving on.
Use the Regex Tester
Open the Regex Tester. Paste your sample text in one panel, write your pattern in the other. Matches appear in real time — no need to click a button between changes. The tool uses the JavaScript regex engine, so the behavior matches what you get in browser and Node.js code.
Common Pitfalls
- Greedy vs lazy quantifiers:
.*matches as much as possible;.*?matches as little as possible. If your capture groups are capturing too much, add a?. - Dot does not match newlines: Unless you use the
s(dotAll) flag,.stops at line breaks. Use[\s\S]as a workaround. - Escaping special characters: Characters like
.,*,+,?,(,),[,],{,},\,|,^,$have special meaning. Escape them with\to match literally. - Anchors:
^matches start of string,$matches end. Use them to prevent partial matches.
Capture Groups
Parentheses () create capture groups. The tester highlights each group in a different shade. Named groups (?<name>...) are supported and make your patterns self-documenting. After matching, you can reference captured values in your code.