Groups, choices and lazy matching
Alternation and groups
Goal: Offer choices with | and repeat sequences with (...) · 8 min
The pipe | means or: cat|dog matches "cat" or "dog". Alternation has the lowest priority, so ^cat|dog$ means "starts with cat" or "ends with dog". Parentheses limit its reach: ^(cat|dog)$ means the whole text is "cat" or "dog".
Parentheses create a group, which does two jobs:
- It bundles characters so that a quantifier or alternation applies to all of them:
(ab)+matches "ab", "abab", "ababab". - It captures the matched text so you can read it afterwards (next lessons).
If you only need bundling, use a non-capturing group (?:…). It behaves the same but does not number the match: (?:Mon|Tues|Wednes)day.
Example: /^(?:\d{1,3}\.){3}\d{1,3}$/ describes an IPv4-looking address such as "192.168.0.1": three times "digits and dot", then digits.
Worked example: Days of the weekend
- Goal: accept exactly "Saturday" or "Sunday".
- Both words end in "day", so factor it out:
(?:Satur|Sun)day. - Anchor it:
^(?:Satur|Sun)day$.
const re = /^(?:Satur|Sun)day$/;
console.log(re.test("Saturday"), re.test("Sunday"), re.test("Monday"));Output:
true true false