A Developer's Guide to Regular Expressions
Regular expressions look like line noise until you can read the handful of pieces they are built from. This guide goes through those pieces and then covers the problems that catch people in practice: differences between languages, slow patterns, and debugging.
Regular expressions are a pattern-matching language built into nearly every programming language. With them you can validate input, parse log files, and perform search-and-replace in a line or two where hand-written string handling would take many more.
Why Regex Matters
At their core, regular expressions solve three problems:
- Validation: Does this string look like an email address? A phone number? A valid hex color?
- Parsing: Extract the timestamp, error code, and message from a log line.
- Search-and-replace: Rename every
getUserById(call tofindUserById(. A regex cannot reliably tell code from comments or strings, so for language-aware renames use your editor's refactoring tools instead.
You could write custom parsing logic for each of these tasks, but regex lets you express the pattern in a single line. The trick is learning to read and write that line.
Basic Syntax: The Building Blocks
Character Classes
Character classes match a single character from a defined set. Square brackets define the set:
[abc] matches 'a', 'b', or 'c'
[a-z] matches any lowercase letter
[A-Za-z] matches any letter
[0-9] matches any digit
[^0-9] matches anything that is NOT a digit
There are also shorthand character classes that save you from typing out the full brackets:
\d same as [0-9] (digit)
\D same as [^0-9] (non-digit)
\w same as [A-Za-z0-9_] (word character)
\W same as [^A-Za-z0-9_] (non-word character)
\s whitespace (space, tab, newline)
\S non-whitespace
. any character except newline
These shorthands vary by language. In JavaScript and Go, \d and \w match ASCII characters. In Python 3, on str patterns, they match Unicode digits and word characters unless you pass re.ASCII. If you validate numbers, [0-9] is the unambiguous choice.
Quantifiers
Quantifiers control how many times a character or group can repeat:
* zero or more
+ one or more
? zero or one (optional)
{3} exactly 3
{2,5} between 2 and 5
{3,} 3 or more
By default, quantifiers are greedy, meaning they match as much as possible. Adding ? after a quantifier makes it lazy (matches as little as possible):
".*" greedy: matches "hello" world "bye" as one match
".*?" lazy: matches "hello" and "bye" separately
Anchors
Anchors do not match characters. They match positions:
^ start of string (or line with 'm' flag)
$ end of string (or line with 'm' flag)
\b word boundary
For example, ^\d{3}$ matches a string that is exactly three digits, nothing more.
Groups and Captures
Parentheses serve two purposes: grouping and capturing.
Basic Groups
// Grouping for quantifiers
(ab)+ matches 'ab', 'abab', 'ababab'...
// Alternation
(cat|dog) matches 'cat' or 'dog'
Named Groups
Named groups make your patterns self-documenting. Instead of referencing captures by index, you give them meaningful names:
// JavaScript named groups
const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = '2026-04-09'.match(pattern);
console.log(match.groups.year); // '2026'
console.log(match.groups.month); // '04'
console.log(match.groups.day); // '09'
Non-Capturing Groups
If you need grouping but do not care about capturing the result, use (?:...):
(?:https?|ftp):// groups the protocol options without capturing
Backreferences
Backreferences let you match the same text that was previously captured:
// Match repeated words
\b(\w+)\s+\1\b matches "the the", "is is", etc.
Lookahead and Lookbehind Assertions
Lookaheads and lookbehinds check for patterns without including them in the match. They are called "zero-width assertions" because they do not consume any characters.
// Positive lookahead: match 'foo' only if followed by 'bar'
foo(?=bar) matches 'foo' in 'foobar', not in 'foobaz'
// Negative lookahead: match 'foo' only if NOT followed by 'bar'
foo(?!bar) matches 'foo' in 'foobaz', not in 'foobar'
// Positive lookbehind: match 'bar' only if preceded by 'foo'
(?<=foo)bar matches 'bar' in 'foobar', not in 'bazbar'
// Negative lookbehind: match 'bar' only if NOT preceded by 'foo'
(?<!foo)bar matches 'bar' in 'bazbar', not in 'foobar'
A practical use case: matching a price value without the dollar sign.
// Extract the number after '$' without including '$' in the match
(?<=\$)\d+\.?\d* matches '42.99' in '$42.99'
Common Regex Recipes
You can try these in the Regex Tester, which uses your browser's JavaScript regex engine. They are starting points, so test them on your own data.
Email Validation (Simplified)
^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$
This accepts most ordinary addresses but is not RFC 5322 compliant, and a matching address may not exist. For forms, use a loose check like this and confirm by sending a message.
URL Matching
https?:\/\/[^\s/$.?#].[^\s]*
Phone Numbers (US Format)
^(\+1)?[\s.\-]?\(?\d{3}\)?[\s.\-]?\d{3}[\s.\-]?\d{4}$
This handles formats like (555) 123-4567, 555.123.4567, +1 555-123-4567, and 5551234567.
IPv4 Address
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$
The octet pattern also accepts leading zeros, such as 010, which some programs interpret as octal. Use a parser when that matters.
Hex Color
^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$
This matches 3-digit shorthand (#fff), 6-digit (#ffffff), and 8-digit with alpha (#ffffff80).
Regex Flavors: JavaScript, Python, and Go
Syntax and features differ between engines. Three examples:
JavaScript
JavaScript uses the RegExp object or literal syntax (/pattern/flags). It supports lookaheads, lookbehinds and named groups (both since ES2018), and Unicode property escapes such as \p{Letter} when the u or v flag is set. Flags include g (global), i (case-insensitive), m (multiline), s (dotAll), u (Unicode), v (Unicode sets), y (sticky), and d (match indices).
// JavaScript regex with flags
const re = /(?<name>\w+)@(?<domain>\w+\.\w+)/gi;
const matches = [...text.matchAll(re)];
matches.forEach(m => console.log(m.groups.name));
Python
Python's re module uses string patterns. Named groups use the syntax (?P<name>...) instead of JavaScript's (?<name>...). Python also supports re.VERBOSE (the x flag), which lets you add whitespace and comments inside your pattern, and since Python 3.11 it supports atomic groups and possessive quantifiers.
# Python verbose regex with comments
import re
pattern = re.compile(r"""
^(?P<year>\d{4}) # Year
-(?P<month>\d{2}) # Month
-(?P<day>\d{2}) # Day
$
""", re.VERBOSE)
match = pattern.match("2026-04-09")
print(match.group("year")) # '2026'
Go
Go's regexp package uses RE2 syntax, which deliberately omits backreferences and lookaheads/lookbehinds. This guarantees linear-time matching, which prevents catastrophic backtracking (more on that below), but it means some patterns that work in JavaScript or Python will not work in Go.
// Go regex (RE2 syntax, no lookaheads)
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
match := re.FindStringSubmatch("2026-04-09")
fmt.Println(match[1]) // "2026"
}
Performance: Catastrophic Backtracking
Backtracking engines, which JavaScript, Python, Java, and most other languages use, can take exponential time on certain patterns with certain inputs. When user input reaches such a pattern, this is a denial-of-service risk known as ReDoS.
The classic example:
// Dangerous pattern: nested quantifiers
^(a+)+$
// Safe input: "aaaaaaaaa" (fast)
// Malicious input: "aaaaaaaaa!" (exponential backtracking)
On that input the engine tries every way of splitting the 'a' characters between the inner and outer repetition before concluding that the '!' prevents a match. The number of ways to split n characters is 2^(n-1): 256 for 9 characters, and about 16.8 million for 25. Each extra character doubles the work.
How to Avoid It
- Avoid nested quantifiers: Patterns like
(a+)+,(a*)*, or(a+)*are red flags. - Use atomic groups or possessive quantifiers where the engine has them:
(?>a+)ora++. These discard backtracking positions once matched. JavaScript has neither. - Be specific: Use
[^"]*instead of.*when matching content between delimiters. - Limit time: JavaScript's built-in regex has no timeout, so run untrusted patterns in a Worker you can terminate, or use an RE2-based library. In Python, the third-party
regexmodule takes atimeoutargument. - Test with adversarial input: Try strings designed to nearly match, especially for any pattern applied to user input.
Debugging Tips
Complex patterns become hard to read quickly. These habits help.
Break Patterns into Parts
Instead of writing one massive pattern, build it incrementally. Start with the simplest version that matches your target, then add constraints one at a time.
// Step 1: Match any digits with dots
[\d.]+
// Step 2: Require the IPv4 structure (4 groups of digits)
\d+\.\d+\.\d+\.\d+
// Step 3: Constrain to valid octet range (0-255)
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.
(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)
Use Comments and Verbose Mode
Python's re.VERBOSE lets you annotate each part of a pattern. JavaScript has no verbose mode as of this update, so build long patterns from named string pieces or put a comment above the line.
Use a Visual Tester
Paste a test string and see what matches, what gets captured, and where groups start and end. The Regex Tester highlights matches as you type and lists capture groups.
Real-World Example: Parsing Log Lines
Suppose you have server log lines like this:
[2026-04-09 14:32:07] ERROR [auth-service] Login failed for user "[email protected]" from 192.168.1.42
Here is a regex that extracts every meaningful field:
const logPattern = /^\[(?<timestamp>[\d\- :]+)\]\s+(?<level>\w+)\s+\[(?<service>[\w\-]+)\]\s+(?<message>.+)$/;
const line = '[2026-04-09 14:32:07] ERROR [auth-service] Login failed for user "[email protected]" from 192.168.1.42';
const match = line.match(logPattern);
console.log(match.groups.timestamp); // '2026-04-09 14:32:07'
console.log(match.groups.level); // 'ERROR'
console.log(match.groups.service); // 'auth-service'
console.log(match.groups.message); // 'Login failed for user "[email protected]" from 192.168.1.42'
You could then parse the message field further to extract the email and IP address using the patterns from the recipes section above.
Wrapping Up
Once you know the building blocks (character classes, quantifiers, anchors, groups, and assertions), most patterns can be read piece by piece. For anything applied to user input, also check how the pattern behaves on near-matches.
To practice, take a log file or a list of inputs you already have, open the Regex Tester, and build a pattern for it one piece at a time.