Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesA regular expression (regex) is a pattern for finding text. Use this cheatsheet to search for a substring, extract pieces, replace repeated text, or check whether an input has a particular shape. The examples below use syntax common to JavaScript and Python, but regex engines, flags, and the APIs that run them can differ. Try a pattern in the application where you intend to use it before relying on the result.
Copy-paste regex examples
These patterns use common JavaScript-style regex syntax. In Python, pass the pattern as a raw string, such as r"d+". A pattern that finds a shape does not necessarily establish that the text is valid under real-world rules.
As an Amazon Associate I earn from qualifying purchases.
| Task | Pattern or replacement | What it does |
|---|---|---|
| Find a run of digits | d+ |
Finds one or more digit characters in flavors that support d. |
| Match a simple identifier | [A-Za-z_][A-Za-z0-9_]* |
Requires an ASCII letter or underscore first, followed by ASCII letters, digits, or underscores. This is a deliberately limited identifier rule. |
| Find a date-shaped substring | bd{4}-d{2}-d{2}b |
Finds a four-digit, two-digit, two-digit shape separated by hyphens. It does not check whether the date exists on a calendar. |
| Match a whole date-shaped input | ^d{4}-d{2}-d{2}$ |
Constrains a match to string or line boundaries in common modes. Prefer a full-match API when available, and account for multiline behavior. |
| Find repeated whitespace | s+ |
Finds one or more whitespace characters as defined by the selected flavor. |
| Replace two or more literal spaces with one | Find: {2,}; replace: one space |
Collapses runs of literal spaces; it does not collapse tabs or all whitespace. |
| Match either color spelling | gr(a|e)y |
Matches gray or grey. |
| Capture a simple key and value | ^([^=]+)=(.*)$ |
Under typical greedy matching, captures the text before and after the first equals sign. Empty values and line breaks may need stricter handling. |
| Match a literal period | . |
Escapes the metacharacter so it means a period, not an arbitrary character. |
Regex syntax at a glance
A regex is a pattern language. As A.M. Kuchling puts it in the Python Regular Expression HOWTO, “Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module.” The same broad building blocks appear in many tools, but not every feature behaves identically in every flavor.
| Syntax | Beginner meaning | Example |
|---|---|---|
cat |
Literal characters, usually matched in sequence. | cat finds the substring “cat”. |
. |
Any character except line terminators in common default modes; flags can change this. | c.t can match “cat” or “cot”. |
[abc] |
One character from a listed set. | [aeiou] matches one listed vowel. |
[a-z] |
One character in a range; range behavior depends on the flavor. | [A-Z] matches an ASCII uppercase letter in common flavors. |
[^,] |
One character outside the set when ^ begins the character class. |
[^,]+ matches a nonempty run without commas. |
d, s, w |
Shorthands for digit, whitespace, and word-like characters; exact character sets can depend on flavor and mode. | d+ finds a digit run. |
^, $ |
Boundary assertions commonly used for the start and end of a string or line. | ^cat$ is commonly used to match a whole line containing “cat”. |
*, +, ? |
Zero or more, one or more, or zero or one repetition of the preceding item. | ab+ matches “ab”, “abb”, and so on, but not just “a”. |
{n}, {n,m} |
Exact or bounded repetition. | d{4} means four digits in common flavors. |
(…) |
Groups a subpattern; capturing groups also save matched text. | ([A-Z]+)-(d+) captures both parts. |
(?:…) |
Groups a subpattern without requesting a capture in flavors that support it. | (?:cat|dog)s? groups the choices and optional final “s”. |
A|B |
Matches either alternative. | cat|dog matches either word; group alternatives when combining them with surrounding syntax. |
|
Escapes a metacharacter or introduces a special sequence. | . matches a literal period. |
How character classes and quantifiers work
Character classes choose one character
Square brackets describe a set of possible characters for a single position. For example, [aeiou] matches one vowel from that list. A range such as [A-Z] is concise, but its exact behavior depends on the regex flavor. Put ^ first inside the brackets to negate the set: [^,] matches one character other than a comma.
#1 Best Overall
Quantifiers control repetition
A quantifier applies to the item immediately before it. Thus d+ means a digit followed by zero or more additional digits, while d{4} requires four digits. Use * for zero or more, + for one or more, and ? for zero or one. Braces let you specify a count or range, such as {2,5}.
Anchors: finding a substring versus matching the whole input
Many search functions look for a match anywhere in the text. The pattern cat can therefore find “cat” inside “concatenate”; it does not by itself validate the entire input. Anchors constrain where a match occurs: ^cat$ is commonly used to match a whole line containing only “cat”. In multiline modes, anchors can refer to line boundaries, so use the target API’s full-match operation when it offers one and whole-input validation matters.
Rank #2
- Used Book in Good Condition
For example, bd{4}-d{2}-d{2}b can locate a date-shaped substring, while ^d{4}-d{2}-d{2}$ constrains a date-shaped input. Neither pattern proves that the month and day form a real calendar date; use a date parser or validator for that rule.
Groups, alternation, and extracting text
Parentheses group parts of a pattern and, by default in common flavors, capture the matched text. In ([A-Z]+)-(d+), the groups capture the uppercase-letter run and the digit run separately. Capture results depend on the API: for example, JavaScript’s match behavior changes when the global flag is used.
Rank #3
The vertical bar means “or.” In gr(a|e)y, the group makes the choice between a and e part of the surrounding word, producing “gray” or “grey”. If parentheses are only needed to group and the captured value is not needed, use a non-capturing group such as (?:cat|dog)s? in flavors that support it. MDN notes that capture groups have a performance cost.
Greedy and non-greedy matching
Quantifiers are generally greedy: they take as much text as possible while still allowing the whole pattern to match. For example, with <b>one</b><b>two</b>, (<b>.*</b>) can span from the first opening tag to the last closing tag. In JavaScript, adding ? after a quantifier makes it non-greedy; (<b>.*?</b>) asks for the shortest compatible match. This can help with simple text patterns, but use an HTML parser to parse HTML structure.
Use regex safely in Python and JavaScript
Python
Python strings and regex patterns both use backslashes. Raw strings avoid most double-escaping confusion, so write re.search(r"d+", text) to search text for a digit run. The Python re module is the engine and API; another application may use a different flavor.
Recommended Free Tools
JavaScript
JavaScript lets you write a regex literal such as /d+/ or construct a RegExp from a string. A string constructor has its own escaping layer, so test the actual pattern in its destination context. Flags also affect behavior, and APIs can return captures differently.
Best Value
A practical routine for building and debugging a pattern
- Write down one exact example the pattern should match and one it must reject.
- Start with literal text, then add one regex construct at a time.
- Test empty input, punctuation, spaces, line breaks, and boundary cases that matter to the task.
- Decide whether you are finding a substring, extracting parts, replacing text, or validating the whole input; choose the appropriate API and boundaries.
- Confirm the destination tool’s regex flavor and flags, then test there before relying on the result.
- Use a parser or dedicated validator when the input has nested structure or domain rules that a text pattern cannot establish.
Further beginner reading
For a guided print introduction, Pearson lists Ben Forta’s Learning Regular Expressions as a 2018 Addison-Wesley Professional title. O’Reilly labels Introducing Regular Expressions beginner level; its Regular Expressions Cookbook, 2nd Edition is marked intermediate to advanced.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




