TL;DR
Three steps: anchor the position (^ $), match the content (\d \w, classes), then control quantity (+ * {n,m}).
Basics
| Syntax | Meaning |
|---|
. | Any character (usually not newline) |
\d / \w / \s | Digit / word char / whitespace |
[abc] / [^abc] | Class / negated class |
^ / $ | Start / end of line |
* / + / ? | 0+ / 1+ / 0 or 1 |
{n,m} | n to m times |
(...) / (?:...) | Capturing / non-capturing group |
| `a | b` | Alternation |
\b | Word boundary |
Common Patterns
| Target | Pattern |
|---|
| Email (simplified) | [\w.+-]+@[\w-]+\.[\w.-]+ |
| URL (simplified) | https?://[^\s]+ |
| Date yyyy-mm-dd | \d{4}-\d{2}-\d{2} |
| IPv4 | (\d{1,3}\.){3}\d{1,3} |
Notes
- Use lazy quantifiers
*? +? to avoid greedy over-matching. - Engines differ: PCRE, ERE (
grep -E), and JavaScript are not identical. - Validate complex patterns in small steps.
Sources
- regular-expressions.info
- MDN Regular Expressions
最后更新:2026-08-02