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
| Pattern | Matches |
abc | Literal 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 |
\d | Digit (equivalent to [0-9]) |
\w | Word character (letters, digits, underscore) |
\s | Whitespace |
Anchors and Quantifiers
| Symbol | Meaning |
^ | Start of string (or line in multiline mode) |
$ | End of string (or line) |
\b | Word 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
| Syntax | Meaning |
(?=...) | 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
| Pattern | Regex |
| 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
| Feature | JavaScript | Python | PCRE |
| Lookbehind | Supported (ES2018+) | Fixed-width only | Variable-length |
| Named group | (?<name>...) | (?P<name>...) | (?<name>...) |
| Flags | /pattern/gi | re.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.