Groups and Alternation
~300 words ยท 2 min read
Groups and Alternation
Once you can match single characters, grouping lets you treat several elements as a unit so you can apply quantifiers or alternatives to the whole group.
Capturing Groups
Parentheses () create a capturing group. The text it matches is stored and can be referenced later โ by backreference or by index in the match result.
/(\d{4})-(\d{2})-(\d{2})/
on "2024-07-05": group 1 = "2024", 2 = "07", 3 = "05"
Non-Capturing Groups
When you only need grouping to apply a quantifier โ not the captured text โ use (?:...). It avoids filling capture slots and is slightly faster.
/(?:https?|ftp):\/\//
matches "http://", "https://", or "ftp://"
Alternation
The pipe | means OR. It has the lowest precedence, so cat|dog matches "cat" or "dog", while ca(t|d) matches "cat" or "cad". Parentheses control the scope.
/apple|orange/ "apple" or "orange"
/gr(a|e)y/ "gray" or "grey"
Alternation is not a character class.
[aeiou]matches one of several single characters;cat|dog|birdmatches one of several whole alternatives. Use classes for single characters, alternation for multi-character choices.
Backreferences
A backreference \1, \2, and so on matches the exact text an earlier capturing group captured. This lets you detect repeats such as doubled words or matching quote characters.
/(\w+)\s\1/ a repeated word: "the the"
/(['"]).*?\1/ quoted string with a matching quote
Named Groups
For readability, name your groups with (?<name>...) and refer back with \k<name>. Named groups make complex patterns far easier to maintain.
/(?<year>\d{4})-(?<month>\d{2})/