Groups & backreferences
Bundle characters with parentheses, branch with alternation, then capture a match and recall it later in the same pattern with a backreference.
Read the rules: Groups: capture & name in the Guide →Drill it: Tricky patterns →
Builds on Anchors & boundaries
What you'll learn
Steps · 13
- 01Bundling with parenthesesBriefing
- 02A group is one unitHunt
- 03A quantifier over a groupHunt
- 04Alternation with the pipeHunt
- 05Highlight the alternativesHunt
- 06Grouping the alternativesHunt
- 07Groups that do not captureHunt
- 08BackreferencesHunt
- 09A five-letter palindromeHunt
- 10A repeated wordHunt
- 11An optional groupHunt
- 12Golf: repeated syllableHunt
- 13Capture and recall, masteredBriefing
Regex groups, alternation and backreferences
Parentheses in a regular expression make a group: several characters treated as one unit. Put a quantifier after the group and it repeats the whole unit, not the last character. Put a pipe | inside and you get alternation, a list of choices where any one may match.
A plain group ( ) also captures. It remembers the exact text it matched, and a backreference such as \1 asks for that same text again later in the pattern. That is how a regex finds repeated letters, matching quote marks or a word typed twice. Groups are numbered by their opening parenthesis, counting from the left.
When you need the grouping but not the memory, write a non-capturing group, (?:...). It groups and branches the same way and keeps the numbering of your other groups tidy. In a hunt, a well-placed group is often what separates a pattern that catches the targets from one that also catches the innocents.
Examples
Catches
- undo
- redo
Spares
- do
- outdo
- undone
The group keeps the choice between
unandreapart from the rest, and the anchors stop longer words.Catches
- 555-0199
- 0199
Spares
- 55-0199
- 555-019
- 5550-199
The
?after the group makes the whole area code optional, dash included, never half of it.Catches
- ha!
- haha!
- hahaha!
Spares
- hah!
- ha
- aha!
The
+after the group repeats the wholeha, not only thea, so a strayhbefore the!is spared.Catches
- "hi"
- 'ok'
- say 'yo'
Spares
- "hi'
- 'ok"
- no quotes
A backreference makes the closing quote match whichever quote opened the text.
Common mistakes
- Leaving alternation unwrapped. The pipe has the lowest priority, so
^red|blue$means^redorblue$; wrap the choices as^(red|blue)$when the anchors must apply to both. - Using square brackets for words.
[red|blue]is a character class that matches one letter from that set (or the pipe itself), not the wordredorblue. - Shifting your backreferences. A new capturing group earlier in the pattern renumbers every group after it, so
\1suddenly points somewhere else; use(?:...)for groups you never recall.
Read the rules: Groups: capture & name in the Guide →Drill it: Tricky patterns →
Read more: Regex backreferences: patterns that remember what they matched →