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 stringNon-Capturing Groups
Group without capturing.
(?:abc) # Non-capturing group
(?:cat|dog) # Match but don't capture
(?:\d+) # Group digits without captureAdvertisement
Named Groups
Name your capture groups.
(?<name>\w+) # Named group "name"
(?P<email>.+@.+) # Python named group
\k<name> # Reference named groupMultiple Groups
Capture multiple parts.
(\d{3})-(\d{4}) # Phone parts
(\w+)@(\w+)\.(\w+) # Email parts
^(\w+)\s+(\w+)$ # First and last nameNested Groups
Groups within groups.
((https?):\/\/.+) # Nested protocol and URL
((\d{3})-(\d{4})) # Nested phone partsGroup Alternation
Alternatives in groups.
(red|green|blue) # Match one color
(Mr|Mrs|Ms)\. # Match title
(jpg|png|gif)$ # Match file extensionPractical 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 nameReplacement 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 dateLast updated: January 2026