re named groups & structured results

Parse text with named groups

Lesson 18 of 20 · 11 min · Module 5: Real-world data

Regular expressions can do more than test if text matches. Named groups pull out each field by name, turning a line of text into a dictionary.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Capture fields with named groups
  • Require a full match
  • Turn text into structured data

The idea

(?P<level>[A-Z]+) captures text into a group called level. match.groupdict() returns all named groups as a dict. Use re.fullmatch to require that the whole line matches, and compile the pattern once with re.compile.

import re
pattern = re.compile(r"(?P<user>\w+)@(?P<domain>[\w.]+)")
print(pattern.fullmatch("[email protected]").groupdict())

01Names beat numbers

match.group(3) breaks as soon as you add a group earlier in the pattern. match.group("level") and groupdict() keep working and document what each part means.

02fullmatch vs search

search finds the pattern anywhere, so "junk 2026-10-18 …" would still match. fullmatch requires the entire string to match, which is what a line parser needs.

import re
print(bool(re.search(r"\d+", "abc123")), bool(re.fullmatch(r"\d+", "abc123")))
Output
True False

03Compile once

re.compile builds the pattern once. Reusing the compiled object in a loop over thousands of lines is faster and keeps the pattern defined in one place.

Your turn

Write parse_line(line) for log lines like 2026-10-18 08:07:03 ERROR Payment service timeout. Return {"date": "2026-10-18", "time": "08:07:03", "level": "ERROR", "message": "Payment service timeout"}, or None if the line does not match. Levels are uppercase words; there may be several spaces after the level. Then write count_levels(text) that returns a dict counting each level, ignoring lines that do not match.

What the checks look for

  • Parses a log line into named fields
  • Allows several spaces after the level
  • Returns None for lines that do not match
  • Counts levels and skips malformed lines
Try it in the editor →

Take this with you

Named groups turn lines of text into dictionaries you can work with.

Go a little further

Return the messages of all ERROR lines that happened between two given times.

Learn Python Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →