regex alternation — | operator and grouping
Quick Answer
# Match "cat" or "dog"
/cat|dog/
# Anchored alternatives (group with parentheses)
/^(cat|dog)$/ # matches exactly "cat" or "dog"
# Non-capturing group
/(?:cat|dog)s/ # matches "cats" or "dogs", group not captured
Usage
Alternation matches one of several patterns at the same position. Without grouping, | applies to the whole expression on each side.
Other causes & fixes
Alternation has lowest precedence
# "cat or dog" — ^ and $ apply to each alternative
/^cat$|^dog$/ # matches "cat" or "dog" at start/end
# WITHOUT outer group: ^ only applies to "cat"
/^cat|dog$/ # matches "cat" at start OR "dog" at end — NOT what you want
# CORRECT: group the alternatives
/^(cat|dog)$/
Capture vs non-capture groups
// Capturing group — result stored in match[1]
'catfish'.match(/(cat|dog)fish/)
// match[0] = 'catfish', match[1] = 'cat'
// Non-capturing group — no match[1]
'catfish'.match(/(?:cat|dog)fish/)
// match[0] = 'catfish'
Match multiple file extensions
// Match .jpg, .jpeg, .png, .gif
/\.(jpg|jpeg|png|gif)$/i
# In Python
import re
re.search(r'\.(jpg|jpeg|png|gif)$', 'image.PNG', re.IGNORECASE)
Related