Regular Expressions: Match, Capture and Parse
This lesson teaches the core of regex through one job: parsing a log line. Each idea is introduced when the job needs it, and the lesson ends with a small log parser that you write yourself. You already know strings and loops from the earlier lessons. The next lesson, Regular Expressions in Practice, uses the same tools to clean raw text and validate fields, and shows how a pattern can become dangerously slow.
After this lesson, you will be able to:
- Write patterns from literal text, character classes, quantifiers and anchors
- Extract fields with groups and named groups, and choose between search, match, fullmatch, findall, finditer and sub
- Parse a log line into a dictionary, with an optional field and a safe result for lines that do not fit
- Predict what greedy and lazy quantifiers match, and fix a pattern that matches too much
- Change how a whole pattern behaves with flags
Before you start
#Why string methods run out
Here are three log lines from a training run. The goal is the loss on each line.
lines = [
"2026-03-14 09:12:07 INFO train epoch=3 step=1200 loss=0.4312 lr=0.001",
"2026-03-14 09:12:09 INFO eval epoch=3 loss=0.5120",
"2026-03-14 09:12:11 ERROR train epoch=3 step=1220 loss=nan lr=0.001",
]
for line in lines:
try:
print(line.split()[6].split("=")[1])
except IndexError as err:
print("IndexError:", err)
# Output:
# 0.4312
# IndexError: list index out of range
# nan0.4312. The second line has no step= field, so index 6 does not exist and Python raises the IndexError. If the eval line had one extra field instead, index 6 would hold the wrong value and nothing would fail. Both problems come from counting positions.loss= followed by a run of non-space characters.import re
lines = [
"2026-03-14 09:12:07 INFO train epoch=3 step=1200 loss=0.4312 lr=0.001",
"2026-03-14 09:12:09 INFO eval epoch=3 loss=0.5120",
"2026-03-14 09:12:11 ERROR train epoch=3 step=1220 loss=nan lr=0.001",
]
for line in lines:
match = re.search(r"loss=(\S+)", line)
print(match.group(1))
# Output:
# 0.4312
# 0.5120
# nanr"loss=(\S+)".#Literal text and character classes
The simplest pattern is plain text. It matches itself. Some characters are special, and the first one you will meet is the dot, which matches any single character.
import re
print(re.findall(r"0.001", "lr=0.001 id=0x001"))
print(re.findall(r"0\.001", "lr=0.001 id=0x001"))
# Output:
# ['0.001', '0x001']
# ['0.001']x in 0x001. A backslash before a special character turns it back into plain text. The special characters are . ^ $ * + ? { } [ ] \ | ( ).^ as the first character negates it.import re
print(re.findall(r"[a-z]+=", "loss=0.4 lr=0.001"))
print(re.findall(r"[0-9]+", "step=1200 loss=0.4312"))
print(re.findall(r"[^ =]+", "step=1200 loss=0.4312"))
# Output:
# ['loss=', 'lr=']
# ['1200', '0', '4312']
# ['step', '1200', 'loss', '0.4312']\d is a digit, \w is a letter, digit or underscore, and \s is whitespace. Their capital forms (\D, \W, \S) mean the opposite, which is why \S+ above means "a run of non-space characters".#Quantifiers and anchors
+ means one or more, * zero or more, ? zero or one, and {3} or {2,4} give exact counts.import re
s = "loss=0.4312 step=1200 delta=-0.02 lr=1e-3"
print(re.findall(r"\d+", s))
print(re.findall(r"\d+\.\d+", s))
print(re.findall(r"-?\d+\.?\d*", s))
# Output:
# ['0', '4312', '1200', '0', '02', '1', '3']
# ['0.4312', '0.02']
# ['0.4312', '1200', '-0.02', '1', '-3']0.4312 at the dot. The second finds only decimals and misses 1200. The third allows an optional minus sign, digits, an optional dot and more digits, so it finds every number but also splits 1e-3 into 1 and -3. Each version answers a slightly different question, and choosing the question is the real work. Scientific notation would need a longer pattern.Two phone-like strings are in the text, and re.findall(r'\d{3}-\d{4}', 'Call 555-1234 or 555-12345678') is run. How many matches come back?
^ is the start of the text, $ the end, and \b the boundary between a word character and a non-word character.import re
print(re.findall(r"cat", "cat concatenate scat"))
print(re.findall(r"\bcat\b", "cat concatenate scat"))
print(re.search(r"^ERROR", "ERROR disk full"))
print(re.search(r"^ERROR", "2026 ERROR"))
# Output:
# ['cat', 'cat', 'cat']
# ['cat']
# <re.Match object; span=(0, 5), match='ERROR'>
# None\bcat\b finds only the whole word. ^ERROR succeeds only at the very start. A failed search returns None, and that is the value you must check for.#Groups and named groups
Parentheses make a group. A group does two jobs: it lets a quantifier apply to several characters, and it remembers the text it matched so you can pull that part out.
import re
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "run on 2026-03-14 ok")
print(m.group(0))
print(m.group(1))
print(m.groups())
print(m.span())
# Output:
# 2026-03-14
# 2026
# ('2026', '03', '14')
# (7, 17)group(0) is the whole match and group(1) is the first set of parentheses. Counting groups gets confusing, so name them. (?P<year>...) gives a group a label, and groupdict() returns every labelled group as a dictionary.import re
pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
m = re.search(pattern, "run on 2026-03-14 ok")
print(m.group("year"))
print(m.groupdict())
# Output:
# 2026
# {'year': '2026', 'month': '03', 'day': '14'}re.findall returns. With no group it returns the matched text. With one group it returns only that group's text. With several groups it returns tuples.import re
t = "price: 50, price: 100"
print(re.findall(r"price: \d+", t))
print(re.findall(r"price: (\d+)", t))
print(re.findall(r"(\d+)-(\d+)", "1-2 3-4"))
# Output:
# ['price: 50', 'price: 100']
# ['50', '100']
# [('1', '2'), ('3', '4')](?:...) so nothing is captured. (?:cat|dog)s finds cats and dogs, while (cat|dog)s would return just cat and dog. The vertical bar means "either".\1 means "the same text that group 1 matched", which is called a backreference, so a repeated word can be collapsed to one copy.import re
print(re.sub(r"\b(\w+) \1\b", r"\1", "the the end"))
# Output:
# the end#The functions: search, match, fullmatch, findall, finditer, sub
re module has several entry points, and picking the right one removes most bugs. They differ in where the pattern must match and in what they return.| Function | Where it must match | Returns |
|---|---|---|
re.search(p, s) | anywhere in s | the first match object, or None |
re.match(p, s) | at the start of s | a match object or None |
re.fullmatch(p, s) | the whole of s | a match object or None |
re.findall(p, s) | everywhere | a list of strings or tuples |
re.finditer(p, s) | everywhere | an iterator of match objects |
re.sub(p, repl, s) | everywhere | a new string with replacements |
re.split(p, s) | everywhere | a list of the pieces between the matches |
import re
text = "epoch 3 loss 0.43, epoch 4 loss 0.39"
print(re.search(r"loss", text))
print(re.match(r"loss", text))
print(re.fullmatch(r"\d+", "123"), re.fullmatch(r"\d+", "123 "))
for m in re.finditer(r"epoch (\d) loss (\d\.\d+)", text):
print(m.start(), m.group(1), m.group(2))
print(re.sub(r"\d\.\d+", "X", text))
print(re.sub(r"epoch (\d)", r"E\1", text))
print(re.split(r"[,;]\s*", "a, b;c, d"))
# Output:
# <re.Match object; span=(8, 12), match='loss'>
# None
# <re.Match object; span=(0, 3), match='123'> None
# 0 3 0.43
# 19 4 0.39
# epoch 3 loss X, epoch 4 loss X
# E3 loss 0.43, E4 loss 0.39
# ['a', 'b', 'c', 'd']re.match returned None because loss is not at position 0. This is the most common surprise, so default to re.search for finding and re.fullmatch for validating. Use finditer when you need positions or several groups per match. In a replacement string, \1 pastes group 1 back in.re.compile. The compiled object has the same methods (search, fullmatch, sub and the rest) without the pattern argument.#Task 1: parse a log line
re.VERBOSE flag lets you spread a pattern over several lines with whitespace ignored, which makes long patterns readable.import re
LOG = re.compile(r"""
(?P<date>\d{4}-\d{2}-\d{2})\s
(?P<time>\d{2}:\d{2}:\d{2})\s
(?P<level>[A-Z]+)\s
(?P<kind>\w+)\s
epoch=(?P<epoch>\d+)\s
(?:step=(?P<step>\d+)\s)?
loss=(?P<loss>\S+)
""", re.VERBOSE)
def parse_line(line):
m = LOG.search(line)
if m is None:
return None
row = m.groupdict()
row["epoch"] = int(row["epoch"])
row["loss"] = float(row["loss"])
return row
lines = [
"2026-03-14 09:12:07 INFO train epoch=3 step=1200 loss=0.4312 lr=0.001",
"2026-03-14 09:12:09 INFO eval epoch=3 loss=0.5120",
"2026-03-14 09:12:11 ERROR train epoch=3 step=1220 loss=nan lr=0.001",
"garbage line",
]
for line in lines:
print(parse_line(line))
# Output:
# {'date': '2026-03-14', 'time': '09:12:07', 'level': 'INFO', 'kind': 'train', 'epoch': 3, 'step': '1200', 'loss': 0.4312}
# {'date': '2026-03-14', 'time': '09:12:09', 'level': 'INFO', 'kind': 'eval', 'epoch': 3, 'step': None, 'loss': 0.512}
# {'date': '2026-03-14', 'time': '09:12:11', 'level': 'ERROR', 'kind': 'train', 'epoch': 3, 'step': '1220', 'loss': nan}
# None(?:...)?, so the eval line without it still matches and step comes back as None. The text nan is not a number to regex, but \S+ accepts it and float("nan") converts it. And a line that does not fit returns None from the function instead of crashing, so the caller decides what to do with bad lines.#Flags
re.compile.import re
blob = "\n".join([
"2026-03-14 09:12:07 INFO train loss=0.43",
"2026-03-14 09:12:11 ERROR train loss=nan",
])
print(re.findall(r"^\S+ \S+ ERROR", blob))
print(re.findall(r"^\S+ \S+ ERROR", blob, re.MULTILINE))
print(re.findall(r"error", blob, re.IGNORECASE))
# Output:
# []
# ['2026-03-14 09:12:11 ERROR']
# ['ERROR']re.MULTILINE makes ^ and $ match at every line, not only at the start and end of the whole string. re.IGNORECASE ignores case. re.DOTALL lets . match a newline, which it normally does not. Combine flags with |, for example re.I | re.M.#Greedy versus lazy
A quantifier is greedy by default: it takes as much text as it can, and gives characters back only when the rest of the pattern would otherwise fail. This is the source of the most common regex bug.
Suppose you want to strip HTML tags out of a scraped review.
import re
html = "<b>Great</b> movie, <i>loved</i> it"
print(re.findall(r"<.*>", html))
print(repr(re.sub(r"<.*>", "", html)))
# Output:
# ['<b>Great</b> movie, <i>loved</i>']
# ' it'.* ran to the end of the string, then backed up to the last >, so one "tag" stretched from the first < to the final >. Putting ? after the quantifier makes it lazy: it takes as little as possible and grows only when needed. A negated class avoids the question entirely.import re
html = "<b>Great</b> movie, <i>loved</i> it"
print(re.findall(r"<.*?>", html))
print(re.findall(r"<[^>]*>", html))
print(re.sub(r"<[^>]*>", "", html))
# Output:
# ['<b>', '</b>', '<i>', '</i>']
# ['<b>', '</b>', '<i>', '</i>']
# Great movie, loved it[^>]* can never run past a >, so it stops at the right place by construction. Prefer it when you are matching "everything up to a delimiter". Lazy .*? is a good second choice, and it can still be fooled by delimiters that nest.What does re.findall(r'"(.*)"', 'label "cat" and label "dog"') return?
#Common mistakes
#Try it
This should return each quoted label from a prompt, one item per quote. It returns a single long string instead. Fix the pattern.
['spam', 'not spam', 'unsure']
Tests: Prints errors: 2 and mean loss: 0.6875 (four finite losses: 0.91, 0.88, 0.5, 0.46). The line without a timestamp is skipped because the pattern does not match it.
#Cheat sheet
| Pattern | Meaning |
|---|---|
abc | the literal text abc |
. | any one character except a newline |
[abc], [a-z], [^abc] | one of these, one in this range, one not in this set |
\d \w \s | digit, word character, whitespace (capitals negate) |
* + ? | zero or more, one or more, zero or one |
{n} {n,m} | exactly n, between n and m |
*? +? | the lazy versions: as little as possible |
^ $ \b | start of text, end of text, word boundary |
(...) (?P<name>...) (?:...) | capturing group, named group, non-capturing group |
a|b | either a or b |
\1 | the same text that group 1 matched |
re.I re.M re.S re.X | ignore case, line anchors, dot matches newline, verbose layout |
#Recap
A regex describes the shape of text, so it survives layout changes that break position-based splitting. You build patterns from literal text, character classes, quantifiers and anchors, and you extract pieces with groups, preferably named ones.
re.search to find, re.fullmatch to check a whole string and re.sub to rewrite. Quantifiers are greedy, so .* swallows as much as it can, and the fix is a lazy quantifier or a class that excludes the delimiter. Flags such as re.MULTILINE change how a pattern reads a text that has several lines.Next: Regular Expressions in Practice uses these tools to clean raw text, validate ID formats and spot patterns that can become dangerously slow.
You must check that `run_id` is exactly `run-` followed by 8 digits and nothing else. Which call is the right one?