Advertisement

Capturing Groups

Capture matched text in parentheses.

(abc)           # Capture "abc"
(\d+)           # Capture one or more digits
([a-z]+)        # Capture lowercase letters
(cat|dog)       # Capture "cat" or "dog"

Backreferences

Reference captured groups.

\1              # Reference first capture group
\2              # Reference second capture group
(\w+)\s+\1      # Match repeated word
(["'])(.*?)\1   # Match quoted string

Non-Capturing Groups

Group without capturing.

(?:abc)         # Non-capturing group
(?:cat|dog)     # Match but don't capture
(?:\d+)         # Group digits without capture
Advertisement

Named Groups

Name your capture groups.

(?<name>\w+)        # Named group "name"
(?P<email>.+@.+)     # Python named group
\k<name>             # Reference named group

Multiple Groups

Capture multiple parts.

(\d{3})-(\d{4})          # Phone parts
(\w+)@(\w+)\.(\w+)       # Email parts
^(\w+)\s+(\w+)$          # First and last name

Nested Groups

Groups within groups.

((https?):\/\/.+)    # Nested protocol and URL
((\d{3})-(\d{4}))    # Nested phone parts

Group Alternation

Alternatives in groups.

(red|green|blue)     # Match one color
(Mr|Mrs|Ms)\.        # Match title
(jpg|png|gif)$       # Match file extension

Practical Examples

Real-world group usage.

(\d{4})-(\d{2})-(\d{2})       # Date: YYYY-MM-DD
(\w+)="([^"]*)"               # HTML attribute
<(\w+)>.*?<\/\1>            # HTML tag pair
([A-Z][a-z]+)\s+([A-Z][a-z]+) # Full name

Replacement with Groups

Use groups in replacements.

# Find: (\w+)\s+(\w+)
# Replace: $2 $1
# Swaps two words

# Find: (\d{4})-(\d{2})-(\d{2})
# Replace: $2/$3/$1
# Reformats date
Last updated: January 2026
Advertisement