Python Regex Named Groups — ELI5

Imagine you’re sorting mail. Each envelope has a name, street address, and city. You could toss them into piles numbered 1, 2, and 3 — but that’s confusing. Better to label the piles: “Name,” “Street,” “City.”

Named groups in regex do the same thing for text matching.

Regular groups use numbers

When you search text with regex, you can grab pieces of what you find. Without names, those pieces just get numbers: group 1, group 2, group 3.

That works, but a month later you’re staring at your code going, “Wait, was group 2 the year or the month?”

Named groups use labels

Instead of numbers, you give each piece a name. Now it’s the “year” group, the “month” group, and the “day” group. Your code reads like English instead of a puzzle.

Why does this matter?

  • Your code is easier to read months later
  • If you rearrange the pattern, the names still work (numbers would break)
  • Other people on your team can understand what each piece means

A quick picture

Think of it like a form:

  • Without named groups: “Box 1: ___ Box 2: ___ Box 3: ___”
  • With named groups: “Name: ___ Email: ___ Phone: ___”

Both capture the same information. One is just much clearer.

One Thing to Remember

Named groups are labels for the parts of text your regex captures — they turn mystery numbers into meaningful names that make your code self-documenting.

pythonregexnamed-groupstext-processing

See Also