Regular expressions are most useful when they solve a clearly defined text problem: checking an input, extracting a field, replacing a repeated format, or finding a suspicious log entry. This regex cookbook gives you reusable patterns for those tasks, plus a disciplined way to test, debug, and maintain them across JavaScript, Python, and command-line workflows.
Overview
A regular expression, often shortened to regex or regexp, describes a pattern that a text-processing engine can search for. The same pattern can behave differently depending on the engine, flags, Unicode mode, and the way a host language represents strings. Treat a regex as a small program: define its input, decide whether you need a full match or a partial search, test normal and abnormal cases, and document the assumptions.
The most common developer tasks fall into four categories:
- Validation: deciding whether an entire value follows an expected format.
- Extraction: finding useful pieces such as an identifier, date, or log field.
- Replacement: changing matching text while preserving selected parts through capture groups.
- Debugging: explaining why a pattern matches too much, too little, or too slowly.
For a broader testing workflow, pair this reference with The Practical Regex Cheat Sheet. The patterns below are deliberately readable rather than maximally compressed.
What to track
Core syntax at a glance
| Syntax | Meaning | Typical use |
|---|---|---|
. | Most characters, depending on mode | Match an unknown single character |
^ and $ | Start and end anchors, with engine-specific line behavior | Limit a match to a string or line |
[abc] | One character from a set | Allow a small list of alternatives |
[^abc] | One character not in a set | Stop at a delimiter or excluded character |
\d, \w, \s | Digit, word character, or whitespace shorthand | Compact ASCII-oriented matching |
*, +, ? | Zero or more, one or more, or optional | Control repetition |
{m,n} | Between m and n repetitions | Apply an explicit length range |
(...) | Capture group | Reuse or return matched text |
(?:...) | Non-capturing group | Group without creating a result field |
(?=...) and (?!...) | Positive and negative lookahead | Require or forbid following text without consuming it |
| | Alternation | Choose between two or more forms |
Practical pattern table
These examples are starting points, not universal definitions. Add domain rules only when the application actually needs them.
| Task | Pattern | Important limitation |
|---|---|---|
| Simple identifier | ^[A-Za-z_][A-Za-z0-9_]*$ | Use a different character policy if identifiers may contain Unicode letters. |
| Digits only | ^[0-9]+$ | Does not allow signs, decimals, spaces, or locale-specific numerals. |
| ISO-like date | ^\d{4}-\d{2}-\d{2}$ | Checks shape, not whether the date exists on a calendar. |
| Basic email shape | ^[^\s@]+@[^\s@]+\.[^\s@]+$ | Useful for a basic input check; do not treat it as a complete email specification. |
| HTTP or HTTPS URL | ^https?://[^\s]+$ | Checks the scheme and absence of whitespace, not URL semantics. |
| Quoted value | "([^"\\]|\\.)*" | Supports escaped characters in a basic quoted-string form. |
| Text before a comma | ^[^,]+ | Does not parse quoted CSV fields or nested formats. |
| Log level field | \b(?:INFO|WARN|ERROR|DEBUG)\b | Adjust the vocabulary to the application’s actual logging format. |
Capture groups for extraction and replacement
Use a capture group when the matched text has a value you need to return or reuse. For example, this pattern extracts a date’s components:
^(\d{4})-(\d{2})-(\d{2})$
In JavaScript, the groups are available from the match result:
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(input);
if (match) {
const [, year, month, day] = match;
}
In Python, named groups make maintenance clearer when a pattern has several fields:
import re
pattern = re.compile(r'^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$')
match = pattern.fullmatch(value)
if match:
parts = match.groupdict()
Prefer non-capturing groups for structure that is not part of the output. This keeps match indexes stable as a pattern evolves.
Escaping and boundaries
Characters such as ., +, *, ?, ^, $, (, ), [, ], {, }, |, and the backslash itself have special meanings. Escape them when you mean the literal character. A literal period is \.; a literal question mark is \?.
Be equally careful when a regex is stored in source code. JavaScript regex literals, JavaScript strings, Python raw strings, and Python ordinary strings have different escaping layers. Test the actual value received by the regex engine rather than assuming the source text represents it correctly.
Cadence and checkpoints
Regexes are easier to maintain when you revisit them at the same points as the data they process. A useful monthly or quarterly checkpoint is enough for many small projects, while a high-volume parser or security-sensitive input path deserves review whenever its input contract changes.
- Record representative inputs. Keep valid examples, invalid examples, empty values, very long values, and values containing non-ASCII characters.
- Test the full-match decision. For validation, use an API or method that requires the entire string to match. A search that finds a valid substring is not the same as validating the complete input.
- Check engine compatibility. Confirm support for lookbehind, named groups, Unicode properties, flags, and other features in every runtime that executes the pattern.
- Measure long inputs. Include repeated, nearly matching strings. These cases can expose excessive backtracking that ordinary examples hide.
- Review escaping at boundaries. Recheck patterns when moving them between source code, JSON configuration, shell commands, or replacement templates.
- Save the reason for each rule. A short comment explaining the accepted format is more valuable than a dense pattern with no context.
For command-line work, tools such as grep, sed, and awk can test patterns quickly, but their regex dialects and options differ. Treat a successful shell test as evidence for that tool, not automatic proof that the same pattern behaves identically in JavaScript or Python.
How to interpret changes
When a pattern matches too much
Start by locating the broadest token. A greedy .* often consumes more text than intended, especially when two delimiters occur on the same line. Replace it with a constrained character class such as [^,]*, or use a lazy quantifier such as .*? only when the surrounding structure makes that safe. Add explicit boundaries and test two adjacent records, not just one.
When a pattern matches too little
Check anchors, case sensitivity, newline handling, and character assumptions first. A pattern using \w may not represent every letter a user can enter. A dot may not match a newline unless the relevant mode is enabled. Also check whether the input contains leading or trailing whitespace and decide deliberately whether to trim it before matching.
When performance degrades
Nested, overlapping quantifiers are a common warning sign. Structures resembling (a+)+ or multiple adjacent wildcards can create many possible paths for a backtracking engine to explore when the input almost matches. Prefer explicit delimiters, bounded repetitions, and mutually exclusive alternatives. Set an input length limit where appropriate, and avoid applying complex regular expressions to untrusted, unbounded text without a performance test.
Regex is not always the right parser. Use a URL parser for URL components, a date library for calendar validity, a JSON parser for JSON, and a CSV-aware parser for quoted CSV. A regex can perform a preliminary shape check, but parsing structured formats with a dedicated parser is usually clearer and safer.
Unicode and portability
Decide whether your requirement is ASCII-only or Unicode-aware. Shorthands such as \d and \w are not interchangeable across engines, and flags that enable Unicode behavior can change character handling. If a pattern is shared between services, document the target runtimes and test characters from the languages your users actually enter.
When to revisit
Revisit a regex whenever the input contract changes, a new runtime or library is introduced, a bug report adds an unseen example, or a parser begins handling larger or less trusted inputs. A monthly or quarterly review is useful for shared coding-cheatsheet patterns and utility code, but production validation should be updated immediately when its accepted format changes.
Use this short update checklist:
- Add the new example to the test set before editing the pattern.
- Write down whether the desired behavior is validation, extraction, or replacement.
- Prefer the smallest change that solves the documented case.
- Run positive, negative, boundary, Unicode, and long-input tests.
- Confirm the pattern in every language or command-line tool that uses it.
- Update the explanation when a group, flag, or limitation changes.
When you need a new regex, begin with one real input and one deliberately failing input. Add the literal text, escape special characters, introduce one rule at a time, and test after each change. That incremental method is usually faster than trying to invent a perfect expression in one pass—and it leaves you with a pattern that another developer can inspect, reuse, and safely revisit.