Python Regex in Practice: search, Groups, Greedy vs Non-Greedy, sub, and a Text-Cleaning Project
Regex is a 'looks like' description for text. This guide covers Python's re module — search vs match, findall, groups, greedy vs non-greedy, sub — and ends with a mini-project that cleans 3 support messages: 3 phones, 2 emails, 3 order numbers extracted, all 3 messages kept. Stdlib only, Python 3.12.3.

Once support messages pile up, handling them by hand stops working: hundreds of notes, some with a phone number, some with an email, some with an order number buried mid-sentence, others with extra spaces and a flurry of exclamation marks. A regular expression is a "looks like" description for text: you tell the computer "a phone number looks like this, an email looks like that", and it fishes them out of the pile for you. This guide covers Python's re module: search, match, findall, groups, greedy vs non-greedy matching, and sub, ending with a real text-cleaning mini-project. Everything uses the Python standard library only — no third-party packages. The code was actually run on Python 3.12.3; the demo script is demo244_zh.py in the draft folder (Chinese version) and the English rerun is rerun_en_demo244_g2.py, and both produce the same numbers. The examples use fictional "Morning Bookstore" support messages; the phone numbers, emails, and order numbers are all made-up demo data.
First, what is a regular expression? It is a tiny language for describing what text looks like: \d means "one digit", \d+ means "one or more digits", and @ just means itself. You do not need to understand the whole passage first — you only describe what the thing you want looks like. In Python, the first thing to do when writing a regex is to prefix it with r to make a raw string, as in r"\d+". Why: in an ordinary string, Python processes the backslash in \d before the regex ever sees it, which causes strange problems; a raw string tells Python "leave my backslashes alone and hand them to the regex untouched". That is rule number one for regex in Python, and every example below uses the r"..." form.
Find one: search vs match
re.search means "look through the whole text", while re.match means "look only at the start". Section 1 of the demo compares them on an order number:
text = "ORD-20261124-001"
print("search for digits:", re.search(r"\d+", text).group())
print("match digits from the start:", re.match(r"\d+", text))
What it does: search finds the first run of digits in the whole string, 20261124, and prints it; match looks only at the start, where it finds the letter O instead of a digit, so it returns None, which is what gets printed. Why it is written this way: search scans from the beginning to the end and stops at the first fit; match stands at the door and only takes one look — if the start does not fit, it reports nothing. This is where beginners most often get confused: the digits are plainly in the text, yet match says there are none, because it never looked further in. How to choose: use search when you are not sure where the thing is, and match when you know it is right at the start. When either function finds something, it returns a match object, and .group() pulls out the matched text; when it finds nothing it returns None, and calling .group() on that raises an error, so real code should check for None first.
Find them all at once: findall
When the first match is not enough, findall grabs every match at once and returns them in a list. Section 2 of the demo looks like this:
print("findall digits:", re.findall(r"\d+", "Bought 3 books for 108 yuan"))
print("findall emails:", re.findall(r"[\w.-]+@[\w.-]+", "Contact xiaohong@example.com or zhangsan@test.org"))
What it does: the first line finds all the numbers in "Bought 3 books for 108 yuan", giving ['3', '108']; the second finds both emails, giving ['xiaohong@example.com', 'zhangsan@test.org']. Why it is written this way: \d+ means "a run of digits", and [\w.-]+@[\w.-]+ is the rough shape of an email — \w means a letter, digit, or underscore, [\w.-] means "any one of these characters", + means one or more, with an @ in the middle and another run after it. Note that findall returns a list of plain strings, not match objects, so you can use the result directly; if nothing matches it returns an empty list [] instead of raising an error, which is more forgiving than search. One more detail: if your pattern contains a group in parentheses, findall returns only what is inside the parentheses, not the whole match — the grouping section below comes back to this trap.
Groups: splitting a match into pieces
Sometimes finding is not enough — you also need the pieces: a date split into year, month, and day, or a phone number split into parts. Parentheses are how you mark groups. Section 3 of the demo splits a date:
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "Order date: 2026-11-24")
print("Whole match:", m.group(0))
print("Group 1 (year):", m.group(1))
print("Group 2 (month):", m.group(2))
print("Group 3 (day):", m.group(3))
print("All groups:", m.groups())
What it does: the pattern (\d{4})-(\d{2})-(\d{2}) means "4 digits, a dash, 2 digits, a dash, 2 digits", and the three pairs of parentheses are three groups. The measured output: the whole match is 2026-11-24, group 1 is 2026, group 2 is 11, group 3 is 24, and all groups are ('2026', '11', '24'). Why it is written this way: group(0) is always the whole match, and group(1), group(2) follow the order the parentheses appear in; \d{4} with braces means "exactly 4", and \d{2} means "exactly 2", which is tidier and less error-prone than writing out four \ds. Groups can also be named, as in (?P<year>\d{4}), and then read back with m.group('year'), so you stop counting positions when there are many groups. And the reminder from the last section: with groups in the pattern, findall returns only the groups — re.findall(r"(\d+)-(\d+)", "2026-11") gives [('2026', '11')] rather than the whole match. If you want the whole match, leave the parentheses out or switch to finditer and take the match objects one by one.
Greedy vs non-greedy: eating a lot or a little
By default a regex is greedy: .* eats as many characters as it possibly can. Section 4 of the demo compares the two behaviours on a small piece of HTML:
html = "<b>bold</b> and <b>italic</b>"
print("Greedy .* matches:", re.findall(r"<b>.*</b>", html))
print("Non-greedy .*? matches:", re.findall(r"<b>.*?</b>", html))
What it does: the greedy version returns a single match, ['<b>bold</b> and <b>italic</b>'], eating all the way from the first <b> to the last </b>; the non-greedy version returns two matches, ['<b>bold</b>', '<b>italic</b>'], one per tag. Why it is written this way: in .*, the dot means "any one character" and * means "zero or more", so together they mean "eat as much as you can"; adding a question mark to make .*? means "stop as soon as you can", quitting at the first place the match can end. This is the most common regex accident: you want to pick out tags or quoted passages one by one, forget the question mark, and the whole passage gets swallowed as a single result. Remember: greedy is the default; add the question mark when you want pieces. One more note: by default the dot does not match a newline, so text spanning lines needs re.DOTALL before the dot will eat line breaks too.
Replacement: sub does the cleaning
After finding things you usually want to change them: mask a phone number, squeeze extra spaces down to one, strip out HTML tags. That is re.sub's job. Section 5 of the demo has three small examples:
phone = "13812345678"
print("Masked phone:", re.sub(r"(\d{3})\d{4}(\d{4})", r"\1****\2", phone))
print("Collapse extra spaces:", re.sub(r"\s+", " ", "Hello there refund please"))
print("Strip HTML tags:", re.sub(r"<[^>]+>", "", "<p>Hello</p><p>Goodbye</p>"))
What it does: the first line masks 13812345678 as 138****5678; the second squeezes "Hello there refund please" into "Hello there refund please"; the third strips the tags from <p>Hello</p><p>Goodbye</p> to leave "HelloGoodbye". Why it is written this way: the masking pattern (\d{3})\d{4}(\d{4}) cuts the 11-digit number into "first 3, middle 4, last 4" groups, and the replacement r"\1****\2" uses \1 for group 1 and \2 for group 2, swapping the middle 4 digits for asterisks; \s+ means "one or more whitespace characters", including spaces and tabs, and the whole run is replaced by a single space; <[^>]+> means "starting with a left angle bracket, ending with a right one, with no right bracket in between", which frames exactly one tag, and replacing it with an empty string deletes it. These three examples cover the three typical uses of replacement: keep the ends and change the middle, collapse a run into one, and delete entirely. Note that sub does not change the original string — it returns a new one, so remember to store the result.
Putting it together: a mini-project that cleans 3 support messages
All the pieces from the first five sections are ready. Now they combine into a real mini-project: read 3 messy support messages, pull out the phone numbers, emails, and order numbers, then clean the messages up and mask the phone numbers. Section 6 of the demo is exactly that:
messages = [
"Hi, I am Xiaoming, phone 13812345678, order ORD-20261124-001, has Python Basics arrived?",
" Hello support!! My email is xiaohong@example.com , order ORD-20261124-002, how do I check my refund? ",
"Phone: 13987654321, backup 15011112222, email zhangsan@test.org, order ORD-20261124-003, can I change the address?",
]
phone_pat = re.compile(r"1[3-9]\d{9}")
email_pat = re.compile(r"[\w.-]+@[\w.-]+")
order_pat = re.compile(r"ORD-\d{8}-\d{3}")
What it does: each of the three patterns handles one kind of thing — a phone number starts with 1, has a second digit from 3 to 9, then 9 more digits, 11 in total; the email pattern is the one from the earlier section; an order number is ORD- plus 8 digits, a dash, and 3 digits. The loop does four things per message: extract with the three patterns, strip leading and trailing whitespace, collapse runs of whitespace to a single space, and mask the phone numbers. The measured output: 3 phone numbers — 13812345678, 13987654321, 15011112222; 2 emails — xiaohong@example.com, zhangsan@test.org; 3 order numbers — ORD-20261124-001, ORD-20261124-002, ORD-20261124-003; and all 3 cleaned messages kept, none dropped. Why it is written this way: re.compile compiles a pattern once so it can be reused many times, which is faster and clearer than calling re.findall with the same pattern over and over; the masking step uses a small function as the replacement — phone_pat.sub(lambda m: m.group()[:3] + "****" + m.group()[7:], s) means "for each phone number found, take the first 3 digits, add 4 asterisks, then the last 4 digits" — which is more flexible than a fixed replacement string. The cleaned messages look like this: the first becomes "Hi, I am Xiaoming, phone 138****5678, order ORD-20261124-001, has Python Basics arrived?"; the second loses its leading, trailing, and doubled spaces; the third has both numbers masked as 139****4321 and 150****2222.

With small changes this mini-project is genuinely usable: swap messages for a few hundred notes read from a file, write the cleaned results to a new file, and count how many of each item you found. The phone pattern 1[3-9]\d{9} is a practical approximation — it assumes an 11-digit number whose second digit is 3 to 9. Strictly validating number ranges would need a current prefix table, but for extraction and cleaning it is enough. The email pattern is an approximation too: it catches ordinary emails but will miss a few exotic-but-legal ones. Extraction and validation are two different jobs — extract with a loose pattern, and validate with a stricter method when it really matters.
Tagging messages: one more practice round
Cleaned messages can go one step further: tag them by content — "asking about a refund", "asking about delivery", "wanting to change an address" — so support staff do not have to read every one. The approach is simple: one small pattern per category, tested with search:
import re
def tag(msg):
if re.search(r"refund", msg):
return "refund"
if re.search(r"arrived|delivery|shipped", msg):
return "delivery"
if re.search(r"address", msg):
return "address"
return "other"
msgs = [
"Order ORD-20261124-001, has Python Basics arrived?",
"Order ORD-20261124-002, how do I check my refund?",
"Order ORD-20261124-003, can I change the address?",
]
for m in msgs:
print(tag(m), ":", m)
What it does: the three messages get tagged "delivery", "refund", and "address". I ran this variant separately and confirmed the output: delivery, refund, address, in that order. Why it is written this way: | means "or", so arrived|delivery|shipped matches if any one of them appears; the order of the checks matters too — the first matching category wins, so if a message mentions both a refund and an address, it lands in whichever category is checked first. Put the most important, most urgent category first. Once tagging is accurate, the next step is counting: how many refund questions this week, how many delivery questions — count them and you have a simple weekly support report. As the tag rules grow, keep them in one list in one place instead of scattered through the code, or changing one rule will mean hunting through the whole file.
Testing your patterns: try ten real lines first
The most reliable way to write a regex is to try it on ten real messages first, then scale up to all of them. However perfect a pattern looks in your head, real data always has surprises: someone writes a phone number as 138-1234-5678 with dashes in the middle; someone puts an email right after a full stop, so the stop sticks to the end of the address; someone uses full-width brackets that a half-width pattern cannot see. The right approach: save ten representative messages in a small file, write one pattern, run it, and check the results one by one. If it is right, keep it; if it is wrong, change the pattern and run it again. Change only one thing at a time, run immediately after each change, and you will know exactly which change fixed the problem. Another good habit is to keep the message that stumped you as a test case: before changing a pattern next time, run those old cases first and confirm you have not broken anything that used to work. The thing a cleaning project fears most is not a pattern that is too simple — it is changing one place, breaking three others, and not noticing. A ten-line test takes less than five minutes and can save a whole day of rework.
There is one more thing to think about when picking test data: do not only pick "normal" messages. Deliberately pick a few "ugly" ones — messages with emoji, mixed-in English abbreviations, chaotic punctuation, or two phone numbers in a single sentence. A pattern that works on clean data is not much of an achievement; one that still holds up on ugly data is. Every time you add a new pattern, ask yourself: could this pattern accidentally catch something else? A pattern like ORD-\d+ for order numbers might also scoop up a year like "ORD-2026"; a bare \d+ for amounts might count the 2026 in a date as a sum of money. Asking that question once makes every pattern you write afterwards more solid.
Quick reference: the symbols
There are not many regex symbols, and this little table covers most patterns you will read: \d is a digit, \w is a letter, digit, or underscore, \s is a whitespace character (space, tab, newline), . is any one character (except newline), + is one or more, * is zero or more, ? is zero or one, {n} is exactly n times, {n,m} is n to m times, [...] is any one character from the brackets, [^...] is any one character not in the brackets, ^ is the start, $ is the end, | is "or", and parentheses mark a group. A question mark after a quantifier makes it non-greedy, as in .*? or .+?. When writing a pattern, start with the simplest version that works on real data, run it, and only then tighten it bit by bit. Writing one long, perfect-looking pattern up front usually means spending ages debugging without knowing which part went wrong.
Five traps beginners hit most
The first trap is forgetting the r prefix: any pattern with a backslash must be a raw string r"...", or Python will process the backslashes first and change the pattern. The second is the difference between match and search: match looks only at the start, so when it says nothing is there, it may simply not have looked further in. The third is that greedy is the default: .* eats all the way to the last possible ending, so write .*? when you want pieces one by one. The fourth is that findall with groups returns only the groups' contents — leave the parentheses out if you want the whole match, or switch to finditer. The fifth is mixing up extraction and validation: a pattern that can fish out emails is not the same as one that can judge whether an email is valid. Extract with a loose pattern; when validation really matters, use a stricter method — or simply send a verification email. The demo script shows the correct form for each of these traps.
Scope and next steps
This guide covers only the basics of Python's re module: searching, extracting, grouping, and replacing, plus one cleaning mini-project. The site already has a general regex guide that covers regex symbols as such, in a different language's context; this guide does not repeat that material and sticks to how re is written, run, and applied to text cleaning in Python. Not covered: lookahead and lookbehind, advanced uses of named groups, and the performance problems that backtracking can cause. Those are intermediate topics, best learned after you have adapted this guide's mini-project to your own version and run it over a few hundred real messages. Suggested next step: turn section 6's mini-project into a version that reads from a file, writes the cleaned messages to a new file, and counts each kind of item; then add one feature — sorting order numbers by date, for example, or grouping all messages from the same phone number together. Those small changes will make you practise grouping and replacing a few more times, which beats reading ten more pages of documentation. The best way to learn regex is exactly this: get it running on real, messy text, watch it pull out what you asked for, and the symbols stop looking like a foreign language.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.