Regular expressions are most useful when they are treated as small, testable programs rather than mysterious one-line puzzles. This regex cookbook gives developers reusable patterns for validation, extraction, and replacement, with practical examples for emails, URLs, dates, identifiers, log fields, and repeated text. It also explains capture groups, engine differences across JavaScript, Python, PHP, and .NET, plus a repeatable workflow for testing and maintaining patterns safely.
Overview
A regular expression describes a search pattern for text. Literal characters match themselves, while metacharacters add rules: ^ anchors a match at the beginning, $ anchors it at the end, \d represents a digit in many engines, and parentheses create groups.
Before copying a regex pattern, define the task. Validation asks whether the entire input follows a format. Extraction asks which part of a larger string should be returned. Replacement asks what text should be changed and whether captured text should be preserved. These are related but not identical jobs.
For example, a validator should normally match the complete input:
^[A-Z]{2}-\d{4}$This pattern accepts a two-letter uppercase prefix, a hyphen, and four digits, such as AB-1234. Without the anchors, the same expression could match that sequence inside a longer string. Anchors are therefore important whenever the requirement is “the whole value must have this shape.”
Regex is appropriate for local, structural checks, but it should not replace domain-specific parsing. A regex can identify the rough shape of an email address or URL; it cannot reliably prove that the address exists or that a URL is safe to request. Use dedicated parsers and application-level validation when semantics, normalization, or security matter.
What to track
Reusable pattern reference
| Task | Pattern | Notes |
|---|---|---|
| Simple identifier | ^[A-Za-z_][A-Za-z0-9_]*$ | Starts with a letter or underscore, then permits letters, digits, and underscores. |
| Hex color | ^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$ | Matches three- or six-digit hexadecimal colors. |
| ISO-like date | ^\d{4}-\d{2}-\d{2}$ | Checks shape only; it does not reject dates such as month 99. |
| Whitespace trimming | ^\s+|\s+$ | Useful for replacement when a trim function is unavailable. |
| Repeated spaces | \s{2,} | Finds runs of two or more whitespace characters. |
| Log key-value field | \buser_id=([^\s]+) | Captures the value after user_id= until the next whitespace. |
| Simple URL shape | https?://[^\s]+ | Finds HTTP or HTTPS-looking text; use a URL parser for full validation. |
| Practical email shape | ^[^\s@]+@[^\s@]+\.[^\s@]+$ | A deliberately broad input check, not a complete email grammar. |
Capture groups and extraction
Capture groups let you identify a part of a match. Consider a date in year-month-day order:
^(\d{4})-(\d{2})-(\d{2})$Group 1 is the year, group 2 is the month, and group 3 is the day. In JavaScript, a match can be inspected like this:
const pattern = /^(\d{4})-(\d{2})-(\d{2})$/;
const result = pattern.exec("2026-11-23");
if (result) {
const [, year, month, day] = result;
console.log({ year, month, day });
}Use noncapturing groups when you need grouping but do not need the value later. In ^(?:https?://)?example\.com$, the ?: prevents the optional protocol from consuming a numbered capture slot. Named groups can make larger expressions easier to maintain, but their syntax and replacement behavior vary by language.
Replacement patterns
Suppose a log contains repeated spaces and you want to normalize them to one space. The search pattern is \s{2,}, and the replacement is a single literal space. In JavaScript:
const normalized = input.replace(/\s{2,}/g, " ");The g flag is important because without it, only the first match is replaced. For a captured replacement, a pattern such as (\w+),\s*(\w+) can turn Doe, Jane into Jane Doe. JavaScript uses replacement references such as $2 $1, while other languages use their own replacement syntax. Test the replacement output, not just the search match.
Cadence and checkpoints
A regex should be checked whenever its input contract changes, not only when an error appears in production. A short monthly or quarterly review is useful for patterns that process user input, imported files, logs, or third-party API responses.
- Record representative examples. Keep normal, boundary, empty, malformed, and unexpectedly long inputs. Remove sensitive data before storing test fixtures.
- Test positive and negative cases. A validator is incomplete if it only proves that valid examples match. Include near misses such as an extra character, missing separator, wrong case, or trailing newline.
- Check the target engine. Run tests in the same language and runtime used by the application. An online regex tester can help explore a pattern, but it is not a substitute for an automated test in the project.
- Review flags explicitly. Confirm whether the pattern needs global matching, case-insensitive matching, multiline anchors, dot-all behavior, or Unicode handling.
- Measure replacement results. For extraction and replacement, verify captured fields and final output separately. A pattern can match correctly while still producing an incorrect replacement.
Keep each pattern next to a short explanation of its intended input. For example, document whether an identifier is ASCII-only, whether newlines are allowed, and whether matching should be case-sensitive. This prevents a future maintainer from broadening a pattern accidentally.
Flavor differences to check
Regex syntax is similar across languages, but compatibility is not universal. JavaScript supports common character classes, lookarounds in modern runtimes, and named groups in supported environments, but its feature set differs from Python, PHP, and .NET. Python commonly uses the re module and raw strings such as r"\d+" to reduce escaping confusion. PHP typically uses PCRE patterns delimited by characters such as ~, with modifiers placed after the closing delimiter. .NET provides its own engine and APIs, including named-group conventions that may differ from another language.
Before sharing a pattern between projects, check lookbehind support, named-group syntax, Unicode behavior, anchor semantics, and replacement references. Also account for the host language's string escaping. A regex written as \d+ may need an additional layer of escaping when embedded in a normal string literal.
How to interpret changes
When a test changes from passing to failing, first classify the change. A new valid input may mean the regex is too narrow. A newly accepted invalid input may mean an anchor, boundary, or character restriction is missing. A change that affects only one language may indicate an engine or escaping difference rather than a business-rule change.
Compare the smallest failing example with the previous version. Remove unrelated text until you have a minimal reproduction. Then inspect each part of the expression from left to right:
- Anchors: Is the pattern matching the entire value or merely finding a substring?
- Character classes: Are accented letters, Unicode digits, hyphens, or underscores expected?
- Quantifiers: Could
*be accepting an empty value where+is required? - Boundaries: Does
\bbehave as expected for the characters in the input? - Groups: Did a new capturing group change numbered references used by the replacement?
- Performance: Could nested repetition or ambiguous alternatives cause excessive backtracking on long input?
Prefer a clear, bounded expression over a clever, permissive one. For example, separate a rough email shape check from email verification, and parse a URL with a URL parser instead of trying to encode every valid URL rule in one pattern. For untrusted, attacker-controlled input, include timeout or input-length safeguards where the runtime supports them, and avoid patterns with unnecessary nested quantifiers.
When to revisit
Revisit a regex immediately when the product adds a new input format, changes normalization rules, upgrades a runtime or regex library, or begins processing data from a new source. Also review it when users report false rejections, when logs contain previously unseen formats, or when a replacement operation changes data unexpectedly.
For recurring maintenance, use a simple quarterly checklist:
- Review the pattern's documented purpose and confirm that it still matches the current input contract.
- Run the saved fixture set, including boundary and invalid cases.
- Test in every supported language or runtime if the pattern is shared across services.
- Inspect performance with realistic and deliberately awkward inputs.
- Record any intentional behavior change in the test name or nearby documentation.
Before publishing or deploying a revised pattern, use a regex tester to inspect matches, groups, and replacements interactively, then commit the same cases to automated tests. A useful maintenance record includes the pattern, flavor, flags, examples that must match, examples that must not match, and the date or reason for the last review. That small amount of context makes this regex cookbook a living reference instead of a snippet copied without verification.
For related debugging workflows, see the Regex Testing and Debugging Guide. If a pattern is being used to inspect structured API data, pair it with an appropriate parser and review the OpenAPI contract testing guide before relying on text matching as a contract.