How to Extract Anything from Text with Regex
Published · 5 min read
Most real-world regex work is extraction. You have a log file, an email thread, a pasted spreadsheet column or a chat export, and somewhere inside it are the values you actually care about: order codes, email addresses, dates, amounts. You do not need a different trick for each one. You need one method that you can apply to any value with a recognisable shape. This guide walks through that method, then applies it to several common cases.
The core idea: every value has a shape
A regular expression does not understand meaning. It cannot tell that a string is a real invoice number or a working email address. What it can do very well is recognise shape: three capital letters, a dash, four digits. If the thing you want to extract has a shape that is different from the text around it, regex can find it. If it does not, for example a person's name inside a free-form sentence, regex is the wrong tool and you should not force it.
So before writing a single character of pattern, look at five or six real examples of the value and ask what they have in common and what makes them stand out from their surroundings. Pay attention to the variations too. Does the code sometimes appear in lowercase? Is the separator always a dash, or sometimes a space? Every variation you notice now is one you will not have to debug later.
Step 1: Describe the value in plain words
Write the description as a short list of pieces, in order. Be specific about counts and allowed characters. For an order code like ABC-1234 the description might be:
- Starts at a word boundary, so it is not glued to other letters.
- Exactly three uppercase letters.
- A literal dash.
- Exactly four digits.
- Ends at a word boundary.
This step feels slow, but it is where most bugs are prevented. If you cannot describe the value in words, you cannot write a reliable pattern for it. The build your own pattern lesson practises exactly this habit.
Step 2: Translate each piece into tokens
Each line of your description maps to a small regex token. Once you know a handful of building blocks, the translation is almost mechanical.
Character classes
Use [A-Z] for one uppercase letter, \d for one digit, [A-Za-z0-9_] or \w for a word character, and a negated set like [^\s] for anything that is not whitespace. The character sets and shorthand classes lessons cover the details.
Quantifiers
Counts become quantifiers: {3} for exactly three, {2,} for two or more, + for one or more, ? for optional. Prefer exact counts when you know them, because loose quantifiers are the most common source of over-matching.
Boundaries
Use \b so the match does not start or end in the middle of a longer word or number. Use ^ and $ only when the value must fill a whole line or string. For extraction you usually want boundaries, not anchors.
Putting the order code description together gives this pattern:
\b[A-Z]{3}-\d{4}\bStep 3: Capture only the part you need
Often the value is easy to locate only because of what sits next to it. A total amount is just a number, but it is the number after Total:. You have two good options.
Capture groups
Match the label and the value, and wrap the value in parentheses. Your code then reads group 1 instead of the whole match. Named groups such as (?<amount>...) make this clearer when there are several values. See the groups lesson.
Total: (\d+(?:\.\d{2})?)Lookbehind
If you want the full match itself to be just the value, use a lookbehind. It checks the label without including it. Lookbehind is supported in modern JavaScript and in Python, though Python requires the lookbehind to have a fixed width.
(?<=Total: )\d+(?:\.\d{2})?Worked examples for common values
Here is the same method applied to values people extract all the time. Each pattern is a practical starting point, not a universal answer, so test it against your own data.
Email addresses
A practical email pattern accepts the addresses people actually type. It is deliberately simpler than the full email standard, which allows unusual forms you will rarely see. The email address pattern in the library has notes on its trade-offs.
[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}Dates in a fixed format
For dates written as day, month and year with slashes, describe the digit counts exactly. This checks shape only, so 31/02/2026 would still match. Validate real calendar dates in code after extracting them.
\b\d{2}/\d{2}/\d{4}\bHashtags
A hashtag is a # followed by word characters. This simple version is limited to ASCII letters and digits; if your text contains other scripts, read the Unicode text lesson before widening it.
#[A-Za-z0-9_]+Text between quotes
Quoted text is a good example of describing what is not allowed. The value is a quote, then any run of characters that are not quotes, then a closing quote. Using the negated set [^"]* instead of .* stops the match at the first closing quote, so two quoted phrases on the same line come back as two separate matches rather than one long one. The text between quotes pattern shows a variant that also handles single quotes.
"[^"]*"Running the pattern in code
Finding every match is short in both JavaScript and Python. In JavaScript, use the g flag with matchAll or match. In Python, use re.findall or re.finditer.
const text = "Orders ABC-1234 and XYZ-0001 shipped; ab-1234 did not.";
const codes = text.match(/\b[A-Z]{3}-\d{4}\b/g) ?? [];
console.log(codes); // ["ABC-1234", "XYZ-0001"]
const invoice = "Subtotal: 40.00\nTotal: 45.50";
const m = invoice.match(/Total: (\d+(?:\.\d{2})?)/);
console.log(m?.[1]); // "45.50"import re
text = "Orders ABC-1234 and XYZ-0001 shipped; ab-1234 did not."
print(re.findall(r"\b[A-Z]{3}-\d{4}\b", text)) # ['ABC-1234', 'XYZ-0001']
invoice = "Subtotal: 40.00\nTotal: 45.50"
m = re.search(r"Total: (\d+(?:\.\d{2})?)", invoice)
print(m.group(1) if m else None) # 45.50Note that in Python, re.findall returns the group contents instead of the whole match when the pattern has capture groups. Use non-capturing groups (?:...) for structure you do not want returned.
Common mistakes and how to avoid them
- Using
.*to bridge gaps: it is greedy and will often swallow far more than you meant. Prefer a specific class such as[^,]*or a lazy.*?, as explained in greedy vs lazy. - Forgetting boundaries: without
\b, a pattern for four digits will happily match part of a twelve-digit number. - Not escaping special characters: a literal dot, plus or bracket must be escaped, for example
\.instead of.. - Testing only on clean samples: paste in a realistic chunk of your messy input, including lines that should not match.
- Expecting regex to validate meaning: it checks shape. Real existence, checksums and calendar validity belong in code.
Putting it into practice
The method stays the same no matter what you extract: look at real examples, describe the shape in plain words, translate each piece into tokens, capture only what you need, and test against messy input. With practice, steps one and two take seconds.
If you would rather start from a working pattern, the pattern library has tested patterns for common formats, and the generator builds a pattern from a description of your data. Everything runs in your browser, so you can paste real text to test against without it leaving your device.
Practise the full method on mixed text with instant feedback. Generic extraction lesson →
Frequently asked questions
- Can regex extract any kind of data?
- Regex can extract any value that has a recognisable shape, such as codes, emails, dates or numbers. It cannot reliably extract values defined only by meaning, like a person's name in free text.
- How do I extract only part of a match?
- Wrap the part you want in a capture group and read that group in your code, or use a lookbehind so the full match contains only the value you need.
- Why does my pattern match too much text?
- Usually because of a greedy `.*` or a missing word boundary. Replace broad wildcards with specific character classes and add `\b` at the edges of the value.
- Does a match mean the value is valid?
- No. A match only means the text has the right shape. Check things like real calendar dates, checksums or whether an address exists separately in code.
Related posts
- Regex for Beginners: A Practical IntroductionLearn regex from scratch: literals, character sets, quantifiers, anchors, groups and flags, with small tested examples in JavaScript and Python.
- How to Clean Messy Data with RegexPractical regex find-and-replace recipes for messy data: whitespace, duplicate words and lines, dates, phone numbers, leftover HTML and CSV fields.
- How to Extract Phone Numbers with RegexRegex patterns to find phone numbers in text: local formats, international E.164 numbers and a loose extractor, plus cleanup in JS and Python.