Why Regex is Hard to Learn
Regular expressions (Regex) can feel like an alien language—a string of symbols that makes your head spin. But its power for handling text is irreplaceable: validating emails, extracting data, batch replacing. A few lines of regex can do the work of dozens of lines of code. The key is to master the common patterns so you can look them up when needed—you don't have to memorize everything.
Common Regex Cheat Sheet
Validation
| Purpose | Pattern |
|---|---|
| ^[\w.-]+@[\w.-]+.\w+$ | |
| Mobile number (China) | ^1[3-9]\d{9}$ |
| URL | ^https?://[\w.-]+(:\d+)?(/.*)?$ |
| ID card number (18 digits) | ^\d{17}[\dXx]$ |
| IP address | ^(\d{1,3}.){3}\d{1,3}$ |
Extraction
| Purpose | Pattern |
|---|---|
| Extract all numbers | \d+ |
| Extract HTML tag content | <(tag)>(.*?)</\1> |
| Extract links | https?://[\w./?=&%-]+ |
| Extract Chinese characters | [\u4e00-\u9fa5]+ |
Replacement
| Purpose | Regex → Replacement |
|---|---|
| Remove blank lines | consecutive newlines + whitespace → single newline |
| Mask phone number | replace the middle four digits with **** |
| CamelCase to snake_case | insert an underscore before uppercase letters |
DocsAll Regex Tester
Use the Regex Tester to debug in real time:
- Open the Regex Tester
- Enter your regex and choose flags (g global, i case-insensitive, m multiline)
- Paste your test text
- See matches highlighted in real time
Writing and testing as you go is far more efficient than writing regex blind. For more regex basics, see the Regex Tutorial.
Common Metacharacters Cheat Sheet
- . Any character (except newline)
- \d digit, \w letter/digit/underscore, \s whitespace
- ^ start of line, $ end of line
- * zero or more, + one or more, ? zero or one
- {n,m} n to m times
- [] character set, () group, | or
Debugging Tips
Test in segments
Build complex regex piece by piece, testing after each addition—it's easier to locate problems that way.
Use non-greedy matching
Greedy matching grabs too much; non-greedy matching (add ? after a quantifier) matches as little as possible, which is often used when extracting content.
Watch your escaping
To match metacharacters like ., *, ? themselves, escape them with a backslash—e.g., use . to match a literal dot.
Don't over-rely on regex
Parsing complex HTML/JSON with regex is error-prone—use a proper parser when you should. Regex is best for text matching with clear rules.
Tips
Build your own cheat sheet of common patterns, then copy and tweak them as needed. Pair that with a tester for real-time validation, and regex isn't that hard.