Regex Pattern Generation and Testing Guide
Regular expressions are powerful but notoriously hard to write correctly. This guide covers common patterns, testing strategies, and tools that help you build reliable regex.
Key Takeaways
- `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
- Nested quantifiers like `(a+)+` can cause exponential time complexity on certain inputs.
- regex101.com**: Interactive testing with explanation of each token
- ## Essential Regex Syntax | Pattern | Matches | Example | |---------|---------|--------| | `.
- Avoid patterns where a failing match must backtrack through exponentially many paths.
Essential Regex Syntax
| Pattern | Matches | Example |
|---|---|---|
. |
Any character (except newline) | a.c → abc, aXc |
\d |
Any digit [0-9] | \d{3} → 123 |
\w |
Word character [a-zA-Z0-9_] | \w+ → hello_world |
\s |
Whitespace | \s+ → spaces, tabs |
^ / $ |
Start / end of string | ^Hello$ → exact match |
* / + / ? |
0+, 1+, 0 or 1 | colou?r → color, colour |
{n,m} |
Between n and m times | \d{2,4} → 12, 1234 |
(...) |
Capture group | (\d{4})-(\d{2}) → groups |
(?:...) |
Non-capturing group | Group without capture overhead |
[abc] |
Character class | [aeiou] → any vowel |
[^abc] |
Negated class | [^0-9] → non-digit |
Common Patterns
Email (Basic)
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This catches 99% of valid emails. Full RFC 5322 validation requires a much more complex pattern.
URL
^https?://[\w.-]+(?:\.[\w]{2,})(?:/[^\s]*)?$
IPv4 Address
^(?:\d{1,3}\.){3}\d{1,3}$
Note: This matches syntax but not value ranges. 999.999.999.999 passes but is not a valid IP.
Testing Strategy
- Positive tests: Strings that should match
- Negative tests: Strings that should not match
- Edge cases: Empty strings, very long strings, unicode, special characters
- Performance: Test with long input strings to catch catastrophic backtracking
Catastrophic Backtracking
Nested quantifiers like (a+)+ can cause exponential time complexity on certain inputs. Avoid patterns where a failing match must backtrack through exponentially many paths. Use possessive quantifiers (a++) or atomic groups when available.
Tools
- regex101.com: Interactive testing with explanation of each token
- Regex visualizers: Show the state machine to spot backtracking risks
- IDE regex search: Test patterns against real files before deploying