Groups and Alternation
Combine options with the pipe, control precedence with parentheses, capture parts of a match, and reuse captures with backreferences.
Welcome back!
Step 1 of 14Learn
Either this or that
A shipping form accepts the words "standard," "express" or "overnight." A character class can't do this, because it matches one character, not a word. Alternation with the pipe symbol | means "or" between whole alternatives:
standard|express|overnightThe engine tries the alternatives left to right at each position and uses the first that works.
Alternation has the lowest precedence of any regex operator: the pipe splits the entire pattern, or the entire group it's in, into pieces. That causes a famous bug. The pattern ^cat|dog$ does not mean "the whole string is cat or dog." It means "^cat OR dog$": a string that starts with cat, or one that ends with dog. So "catalog" and "hotdog" both match.
The fix is to group the alternatives: ^(cat|dog)$. Now the anchors apply to the group as a whole.
The same applies inside longer patterns. gray|grey hound means "gray" or "grey hound." To mean "gray hound" or "grey hound," write gr(a|e)y hound, or better, use a character class: gr[ae]y hound. Use a class when choosing between single characters, and alternation when choosing between longer sequences.
Step 2 of 14Practice · Sort into groups
Which strings does ^cat|dog$ match (no flags)?
Tap an item, then tap its group (or drag it there).
Step 3 of 14Learn
Parentheses do three jobs
Parentheses in regex create a group, and groups do three different jobs:
- Scope for alternation.
(cat|dog)smatches "cats" or "dogs." - Scope for quantifiers.
(ha)+matches "ha," "haha," "hahaha." Without the group,ha+means "h followed by one or more a." - Capturing. The engine remembers the text each group matched, so your code can extract it.
Groups are numbered by their opening parenthesis, counting from the left, starting at 1. In (\d{4})-(\d{2})-(\d{2}) applied to "2026-03-14," group 1 is "2026," group 2 is "03" and group 3 is "14." Group 0 always means the whole match.
In JavaScript:
const m = "Due 2026-03-14".match(/(\d{4})-(\d{2})-(\d{2})/);
m[0]; // "2026-03-14"
m[1]; // "2026"
m[3]; // "14"Nested groups count by opening parenthesis too: in ((\d{3})-(\d{4})), group 1 is the whole phone number, group 2 the first three digits and group 3 the last four.
If a group is optional and doesn't participate in the match, its value is undefined in JavaScript or None in Python, so check before using it.
Step 4 of 14Practice · Diagram
Numbering groups in ((\d{4})-(\d{2}))-(\d{2})
Groups are numbered by their opening parenthesis, counting from the left. Group 0 is always the whole match.
Which group captures the month?
Tap the shape that answers the question, then press Check.
- Group 0: whole match
2026-03-14
- Group 1: year-month
2026-03
- Group 4: day
14
- Group 2: year
2026
- Group 3: month
03
Step 5 of 14Practice · Work it out
In the pattern (\w+)@((\w+)\.(com|org)), what is the number of the group that captures just the domain name before the dot (for example "example" in "ana@example.com")?
Step 6 of 14Learn
Non-capturing groups
Sometimes you need parentheses only for grouping, not for capturing. Capturing has small costs: it uses memory, it renumbers every later group, and it clutters results. A non-capturing group (?:...) groups without remembering:
(?:https?|ftp)://(\S+)Here the first group just limits the alternation to the protocol. Because it's non-capturing, the URL's remainder is group 1, not group 2.
This matters most when patterns evolve. Suppose your code reads the year from group 1 of (\d{4})-(\d{2}). Later someone adds an optional prefix with a capturing group, (FY)?(\d{4})-(\d{2}), and now the year is group 2. Every piece of code using group 1 silently breaks. Writing the prefix as (?:FY)? keeps the numbering stable. Named groups, in the next lesson, solve the numbering problem even more robustly.
A good habit: use (?:...) by default whenever you group for structure, and plain parentheses only for the parts you actually intend to extract.
Step 7 of 14Compare
Capturing vs. non-capturing groups
| Aspect | ( ... ) | (?: ... ) |
|---|---|---|
| Groups for | and quantifiers | Yes | Yes |
| Gets a number | Yes | No |
| Text available later | Yes: $1, \1, m[1] | No |
| Use when | You need the text | You only need the grouping |
Step 8 of 14Practice · Fill in the blanks
Fill in the blanks
A group written as (?:...) groups part of a pattern without it, so it does not affect the numbering of later groups.
Step 9 of 14Learn
Backreferences: matching the same text again
A backreference matches the exact text that an earlier group captured. In most flavors it is written \1 for group 1, \2 for group 2, and so on.
A classic use is finding accidentally doubled words, like "the the":
\b(\w+)\s+\1\bGroup 1 captures a word; \s+ matches the space; \1 must match the same word again. It finds "the the" and "is is," but not "the then," because \1 requires exactly the captured text and the final \b stops it from matching the start of a longer word.
Other uses:
- Matching quotes that must close with the same character they opened with:
(['"]).*?\1matches'hi'and"hi"but not'hi". - Finding repeated characters:
(.)\1matches "ll" in "hello" or "oo" in "book."
Note the difference from a quantifier: (\d)\1\1 matches three identical digits like "777," while \d{3} matches any three digits like "472." A backreference repeats the matched text; a quantifier repeats the pattern.
Step 10 of 14Practice · Diagram
\b(\w+)\s+\1\b finds "the the"
In "the then", which step fails?
Tap the shape that answers the question, then press Check.
- (\w+) captures "the"
- \s+ matches the space
- \1 must equal "the"
A backreference matches the same TEXT again, not the same pattern.
- Doubled word found
Step 11 of 14Practice · Match the pairs
Match each pattern to a string it matches completely.
Tap an answer, then tap the place where it belongs (or drag it there).
(\d)\1\d\d(ab)+(\w+) \1
Step 12 of 14Practice · Code challenge
Write parseDate(text) that finds the first date written as YYYY-MM-DD anywhere in text and returns an array of three numbers [year, month, day]. If there is no date, return null. Use capture groups.
parseDate("Invoice due 2026-03-14, pay soon")parseDate("1999-12-31")parseDate("no date here")parseDate("from 2025-01-05 to 2025-02-07")
Step 13 of 14Note
Step 14 of 14Practice · Choose one
Which pattern matches exactly the strings "jpg", "jpeg", "png" and "gif" when testing a whole file extension?
Lesson complete!