Overview

Regular expressions (regex) are a compact language for describing text patterns. They appear in validation, search-and-replace, log parsing, and route matching. This tutorial builds from simple character matches to lookaheads and named groups.

Literal and Character Classes

PatternMatches
abcLiteral sequence "abc"
.Any character except newline
[abc]a, b, or c
[^abc]Any character except a, b, or c
[a-z]Any lowercase letter
[0-9]Any digit
\dDigit (equivalent to [0-9])
\wWord character (letters, digits, underscore)
\sWhitespace

Anchors and Quantifiers

SymbolMeaning
^Start of string (or line in multiline mode)
$End of string (or line)
\bWord boundary
*Zero or more
+One or more
?Zero or one
{3}Exactly three
{2,5}Between two and five
{2,}Two or more

Greedy vs Lazy

<.+>    greedy — matches to the last ">"
<.+?>   lazy — matches to the first ">"

Groups and Alternation

(abc)+             one or more repetitions of "abc"
(cat|dog)          "cat" or "dog"
(\d{4})-(\d{2})    captures year and month separately
(?:abc)            non-capturing group

Lookarounds

SyntaxMeaning
(?=...)Positive lookahead
(?!...)Negative lookahead
(?<=...)Positive lookbehind
(?<!...)Negative lookbehind
# Match "100" only when followed by "px"
\d+(?=px)

# Match a price only when not preceded by "$"
(?<!\$)\d+\.\d{2}

Named Groups

(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})
# Python
import re
m = re.match(r"(?P<year>\d{4})-(?P<month>\d{2})", "2026-09-11")
print(m.group("year"), m.group("month"))

# JavaScript
const m = "2026-09-11".match(/(?<year>\d{4})-(?<month>\d{2})/);
console.log(m.groups.year);

Practical Patterns

PatternRegex
Email (simplified)^[\w.+-]+@[\w-]+\.[\w.-]+$
IPv4^(\d{1,3}\.){3}\d{1,3}$
ISO date^\d{4}-\d{2}-\d{2}$
URL^https?://[\w.-]+(:\d+)?(/.*)?$
Hex color^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$

Language Differences

FeatureJavaScriptPythonPCRE
LookbehindSupported (ES2018+)Fixed-width onlyVariable-length
Named group(?<name>...)(?P<name>...)(?<name>...)
Flags/pattern/gire.I | re.M(?i)(?m)

Testing Tools

Use regex101.com to test patterns interactively. It explains each token and supports JavaScript, Python, PCRE, and Go.