examples/regex/capture.py
from __future__ import print_function
import re

line = 'There is a phone number 12345 in this row and an age: 23'

match = re.search(r'age: \d+', line)
if match:
  print(match.group(0))  # age: 23


match = re.search(r'age: (\d+)', line)
if match:
    print(match.group(0))  # age: 23
    print(match.group(1))  # 23      the first group of parentheses

    print(match.groups())  # ('23',)
    print(len(match.groups()))  # 1

match = re.search(r'(age): (\d+)', line)
if match:
    print(match.group(0))  # age: 23
    print(match.group(1))  # age     the first group of parentheses
    print(match.group(2))  # 23      the second group of parentheses

    # print(match.group(3))  # IndexError: no such group
    print(match.groups())  # ('age', '23')
    print(len(match.groups()))  # 2

# Some groups might match '' or even not match at all, in which case we get None
# in the appropriate match.group() call and in the match.groups() call

Parentheses in the regular expression can enclose any sub-expression. Whatever this sub-expression matches will be saved and can be accessed using the group() method. The parentheses are numbered according to their opening (.