0PricingLogin
Learn AI with Python · Lesson

Capturing Groups and Named Groups

Parentheses for capture, (?P ...) named groups, re.fullmatch(), lookahead/lookbehind.

Why Groups?

Groups let you isolate parts of a match so you can extract exactly the piece you want — the area code from a phone number, the year from a date, the username from an email.

This lesson covers capturing, named, non-capturing groups, and lookarounds.

Capturing Groups with ( )

Wrap part of a pattern in parentheses to capture it. The whole match plus each group becomes accessible on the Match object.

import re

m = re.search("(\d{4})-(\d{2})-(\d{2})", "Date: 2026-05-29")
print(m.group())    # "2026-05-29" (whole match)
print(m.group(1))   # "2026"
print(m.group(2))   # "05"

All lessons in this course

  1. Regex Patterns and Character Classes
  2. re Module: search, match, findall, sub
  3. Capturing Groups and Named Groups
  4. Text Cleaning for AI with Regex
← Back to Learn AI with Python