A regular expression is a pattern language for finding or checking the shape of text.
Use matching, searching and character patterns, and separate a matching shape from a valid business value.
Are we finding a log-shaped fragment inside a message, or validating the entire line? That choice comes before writing the pattern. We will compare search and full matching, build the pattern one field at a time, and separate textual shape from facts such as calendar validity.

Quarry's yard can classify and decode the supported sample files, recording
its encoding choice. What comes out is
text — a lot of it server logs, which look structured but have nothing
enforcing that structure. Somewhere in 40,000 lines there's a stack trace, a
line with two stray leading spaces, or a service that logs NOTICE because
someone thought it sounded friendlier than INFO. This section builds the
extractor, the part of Quarry that turns a line of text into typed fields.
Its first job is the humblest one: deciding whether a line is a log line.
Spot a PAN number on a KYC form
An Indian PAN looks like ABCDE1234F: five uppercase letters, four digits, one
uppercase letter. A character class names a kind of character, and a
quantifier right after it says how many:
[A-Z]{5} is "a letter A–Z, five times in a row". \d{4} is "a digit, four
times". Lowercase fails because the class only allows capitals; the third
value fails because it only has three digits where four are required. So far
so good — but re.search only needs the pattern to fit somewhere:
A PAN with junk stuck on either end is wrongly accepted. Run it, see both results print True, then fix the check so only an exact PAN passes.
A form field should hold nothing but a PAN. re.fullmatch is the honest
tool for that: it says exactly what you mean, and nobody reading the code has
to wonder whether a stray character could sneak past.
Preparing this topic’s interactive investigation…
Pull every rupee amount out of a UPI SMS
+ means "one or more", so \d+ grabs a whole run of digits, not just one.
That's greedy: it takes as many digits as it can before giving up.
import re
sms = "Paid Rs.250.00 to Raju. Avl bal Rs.4200.00"
print(re.findall(r"\d+", sms))To keep an amount whole, the pattern has to say "digits, then a dot, then
digits" as one shape — \d+\.\d+:
A pattern matches characters, not the meaning you have in your head. If you want "an amount", you have to spell out its exact shape — Python doesn't know what a rupee amount looks like until you tell it.
Greedy and lazy, in one line
+, * and friends take as much as possible by default. Put a ? right
after one and it takes as little as possible instead:
Greedy .* races to the end of the line and backs off until a closing "
fits — landing on the last one. Lazy .*? stops at the first " it can.
Neither is "more correct"; they answer different questions. The next lesson
goes much deeper into what that choice costs.
Separate shape validation from meaning
fullmatch means that the pattern consumed the entire input. It does not mean that the input describes a real date, account or measurement. A timestamp pattern can accept February 31 because each numeric field has the right width.
The second input passes the shape check and fails the calendar check. The third needs a policy: reject a noncanonical spelling, or normalize it with a deliberately chosen parser. Do not quietly relax the regex and assume that semantic validation followed.
Character classes also express a policy. In Python string patterns, \d accepts Unicode decimal digits, not only 0–9; \w includes Unicode word characters and underscore. An ASCII identifier protocol should say [0-9] and its allowed letter range explicitly, or use an appropriate ASCII flag. The PAN-shaped example illustrates matching syntax; checking that shape does not establish that an identifier was issued or is valid under every domain rule.
Build a rejection table before a pattern: one valid input, one missing separator, one extra prefix, one extra suffix, one non-ASCII digit, and one impossible date. Mark whether each should fail shape validation or later semantic validation. Then implement those two stages separately. This makes a failing test tell you which contract was violated instead of merely saying “the regex is wrong”.
Reference: fullmatch and Unicode character classes.
Make sure a server line really is one of Quarry's logs
Quarry's format, element by element:
2026-09-14 08:15:02 WARN [auth] login failed user=maya took=312ms
└─ date ─┘ └ time ┘ └lvl┘ └comp┘ └──────── message ────────┘- date —
\d{4}-\d{2}-\d{2} - time —
\d{2}:\d{2}:\d{2} - level — one of four words.
|means "or":(DEBUG|INFO|WARN|ERROR). Parentheses keep the|from splitting the whole pattern — groups get a lesson of their own next. - component — a literal
[, a lowercase letter, then letters/digits/ hyphens, then a literal]. Brackets are special, so escape them:\[[a-z][a-z0-9-]*\]. - message — at least one more character:
.+
Each rejection fails for a different reason: leading spaces, an unknown level,
a traceback with no timestamp at all. fullmatch is what makes validation
honest — search would happily approve a line with junk around a valid core,
exactly like the PAN above.
Backslash is special to both Python strings and regex, which is where the
next bug hides. Without the r prefix, Python processes escapes first and
hands re whatever is left:
ERROR is plainly in the line, but this prints "missing". Run it, work out what Python did to the pattern, then fix it with one character.
\b is a word boundary: a zero-width position between a word character
and a non-word one. r"\bERROR\b" finds ERROR but not the ERROR hiding
inside TERRORS. Make r"..." a reflex for every pattern and this whole
class of bug disappears.
Watching the engine work
Knowing what re.search actually does explains every surprise later in this
section. For each start position it walks the pattern, consuming characters
while they fit, and gives up on that position only once nothing else can be
tried — then moves one character to the right. Here's that loop written by
hand for \d+ms against "took=312ms":
The engine is left-to-right and first-wins — it reports the leftmost
match, not the "best" one. A pattern 19 characters wide (the timestamp) has
exactly one place to sit on a 19-character line, which is all fullmatch ever
tries. A short pattern on a long line can start almost anywhere, so an
unanchored search that fails pays for every one of those attempts.
Quick practice
import re
print(re.findall(r"ab+", "abbb ab abab a"))import re
p = r"\[[a-z][a-z0-9-]*\]"
print([bool(re.fullmatch(p, s)) for s in ["[db]", "[Auth]", "[2fa]", "[disk-io]"]])import re
print(bool(re.match(r"\d+", "312ms")), bool(re.fullmatch(r"\d+", "312ms")))🎯 Your turn
Write is_log_line(line) — Quarry's first gate. It returns True only when
the whole line is in Quarry's format (date, time, one of
DEBUG/INFO/WARN/ERROR, a bracketed lowercase component, and a
non-empty message), and False otherwise:
is_log_line("2026-09-14 08:15:02 WARN [auth] login failed user=maya")→Trueis_log_line(" 2026-09-14 08:15:02 INFO [db] pool ready")→Falseis_log_line("2026-09-14 08:15:02 NOTICE [auth] hi")→False
Hint — build the pattern as a raw string, one element at a time, and use
re.fullmatch so nothing is allowed before or after it. Wrap the result in
bool(...) — the grader wants True/False, not a match object.
Then press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write has_digit(text) returning True if text contains at least one digit anywhere, and False otherwise. Use re.search with \d.
Write count_errors(lines) returning how many lines contain ERROR as a whole word. TERRORS and ERRORS do not count; ERROR: does. Use the word boundary \b.
Quarry's operators paste ticket ids into messages: QRY- followed by 3 to 5 digits. Write ticket_ids(text) returning every id in order, as a list. A digit run longer than 5 is not an id, so QRY-123456 must not produce anything.
Quarry's component names must: be 2 to 20 characters long; start with a lowercase letter; contain only lowercase letters, digits and hyphens; and not end with a hyphen. Write valid_component(name) returning True/False, using one pattern and re.fullmatch.
Write level_counts(lines) returning a dict mapping each log level to how many valid Quarry log lines carry it. Validate each line with the full Quarry pattern (date, time, level, [component], message) and skip anything that fails. Levels that never appear are left out of the dict.
A teammate validates log lines with re.search(LOG_LINE, line) and says the tests pass. Explain what kind of bad line their version would wrongly accept, and why re.fullmatch is the better choice for validation while re.search is right for finding.