Grouping with Parentheses
You'll learn how to use parentheses in regular expressions to group subpatterns together and control how operators apply.
What Grouping Does
In regular expressions, parentheses () serve two main purposes: they group parts of your pattern together so you can apply operators to the entire group, and they control the scope of alternation (the pipe operator you just learned).
Think of parentheses like mathematical parentheses. Just as 2 * (3 + 4) groups the addition first, regex parentheses let you say "treat this whole chunk as one unit."
Controlling Alternation Scope
Without parentheses, the pipe operator | applies to everything on its left and right. But often you want alternation within just part of your pattern:
// Without grouping - matches entire alternatives
const regex1 = /cat|dog food/;
regex1.test("cat"); // true (matches "cat")
regex1.test("dog food"); // true (matches "dog food")
regex1.test("cat food"); // true (matches "cat", ignores rest)
// With grouping - alternation only applies inside parentheses
const regex2 = /(cat|dog) food/;
regex2.test("cat food"); // true
regex2.test("dog food"); // true
regex2.test("cat"); // false (requires " food" after)
Grouping for Operator Scope
Parentheses let you apply other operators to entire subpatterns as a single unit:
// Group before applying operators
const repeatGroup = /(ha)+/;
repeatGroup.test("hahaha"); // true - repeats the entire "ha"
repeatGroup.test("haaa"); // false - "a" alone doesn't count
Key Takeaway: Parentheses () group subpatterns together, letting you control where alternation applies and treat multiple characters as a single unit for operators.