Dev
Regex Practical Handbook: 20 Most Common Matching Patterns
2025-04-28Dev
What Are Regular Expressions?
Regular expressions (regex) use special character sequences to describe text patterns. They help find, match, and replace content following specific rules in large texts.
Basic Syntax Overview
Metacharacters - `.` matches any single character - `\d` matches digits [0-9] - `\w` matches word characters [a-zA-Z0-9_] - `\s` matches whitespace - `^` matches line start, `$` matches line end
Quantifiers - `*` zero or more, `+` one or more, `?` zero or one - `{n}` exactly n, `{n,m}` between n and m
20 Practical Patterns
- Email: `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
- URL: `https?://[\w\-]+(\.[\w\-]+)+[\w\-.,@?^=%&:/~+#]*`
- IPv4: `^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$`
- Date (YYYY-MM-DD): `^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$`
- Strong Password: `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$`
- HEX Color: `^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$`
- Currency Amount: `^\d+(\.\d{1,2})?$`
- Username (4-16 chars): `^[a-zA-Z0-9_]{4,16}$`
- File Extension: `\.([a-zA-Z0-9]+)$`
- HTML Tags: `<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)`
- Empty Lines: `^\s*\n`
- Duplicate Words: `\b(\w+)\s+\1\b`
- Markdown Links: `\[([^\]]+)\]\(([^)]+)\)`
- JSON Keys: `"([^"]+)"\s*:`
- Phone (International): `^\+?[1-9]\d{1,14}$`
- Trim Whitespace: `^\s+|\s+$`
- Number with Commas: `\B(?=(\d{3})+(?!\d))`
- CamelCase Split: `([A-Z])`
- Credit Card: `^\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}$`
- Time (HH:MM): `^([01]\d|2[0-3]):[0-5]\d$`
Debugging Tips
- Start simple, add complexity gradually
- Use online testers for real-time feedback
- Add comments for complex patterns
- Watch for catastrophic backtracking with nested quantifiers
YAKOOAITOOLS' regex tester provides real-time highlighting, group details, common pattern insertion, and multi-language support.