๐Ÿ” 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.

Example: \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

SymbolMeaningExampleMatches
\dDigit\d+"123","4567"
\wWord char\w+"hello_world"
\sWhitespacea\sb"a b","a\tb"
.Any charh.t"hat","hit"
[abc]a, b, or c[aeiou]Any vowel

Quantifiers

SymbolMeaning
+One or more
*Zero or more
?Zero or one
{3}Exactly 3
{2,4}2 to 4

Anchors: Position, Not Characters

SymbolMeaning
^Start of string (or line in m mode)
$End of string (or line in m mode)
\bWord boundary

Common Regex Patterns

Use CasePattern
Email[\w.-]+@[\w.-]+\.\w+
Phone (China)1[3-9]\d{9}
Date yyyy-MM-dd\d{4}-\d{2}-\d{2}
URLhttps?://[\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 Tester

FAQ

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 โ†’