๐ Regular Expressions: The Complete Guide
From metacharacters to lookaheads โ master regex in 30 minutes
What Are Regular Expressions?
A regular expression (regex) is a pattern-matching language โ a concise way to describe what text you're looking for. It's not a programming language, but a text processing tool embedded in virtually every programming language.
\d{4}-\d{2}-\d{2} matches "2026-07-25" โ 4 digits + dash + 2 digits + dash + 2 digits. One line replaces dozens of character-by-character loops.
Basic Metacharacters
| Symbol | Meaning | Example | Matches |
|---|---|---|---|
\d | Digit | \d+ | "123","4567" |
\w | Word char | \w+ | "hello_world" |
\s | Whitespace | a\sb | "a b","a\tb" |
. | Any char | h.t | "hat","hit" |
[abc] | a, b, or c | [aeiou] | Any vowel |
Quantifiers
| Symbol | Meaning |
|---|---|
+ | One or more |
* | Zero or more |
? | Zero or one |
{3} | Exactly 3 |
{2,4} | 2 to 4 |
Anchors: Position, Not Characters
| Symbol | Meaning |
|---|---|
^ | Start of string (or line in m mode) |
$ | End of string (or line in m mode) |
\b | Word boundary |
Common Regex Patterns
| Use Case | Pattern |
|---|---|
[\w.-]+@[\w.-]+\.\w+ | |
| Phone (China) | 1[3-9]\d{9} |
| Date yyyy-MM-dd | \d{4}-\d{2}-\d{2} |
| URL | https?://[\w./-]+ |
| IP Address | \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} |
Common Pitfalls
Greedy vs Lazy
<.+> matches <div>hello</div> greedily (the entire string). Add ? for lazy matching: <.+?> only matches <div>.
Dot Doesn't Match Newlines
Use [\s\S] or the s (dotAll) flag to match across lines.
Don't Parse HTML with Regex
Regex can't handle arbitrary nesting. Use a proper parser for HTML/JSON/XML.
๐ Test your regex now
Real-time highlighting, g/i/m flags, Chinese character support
๐ Open Regex TesterFAQ
Q: How do I match Chinese characters?
[\u4e00-\u9fff] matches basic CJK characters. Use the u flag with \p{Script=Han} in modern regex engines.
Q: Why is my regex slow?
Avoid nested quantifiers like (a+)+b โ they cause catastrophic backtracking. Simplify: a+b does the same thing.
๐ Related: JSON Formatter โ ยท Base64 Encoder โ