TutreNews Learn

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:

  1. It bundles characters so that a quantifier or alternation applies to all of them: (ab)+ matches "ab", "abab", "ababab".
  2. 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

  1. Goal: accept exactly "Saturday" or "Sunday".
  2. Both words end in "day", so factor it out: (?:Satur|Sun)day.
  3. 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