Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Syntax and Matching

Alternation and Precedence

Learn how the regex alternation operator | chooses between options, why it has the lowest precedence, how to group alternatives with parentheses, and how ordering changes the result.

The pipe | means or. cat|dog matches either cat or dog. It is simple until you combine it with other pieces, and then one rule decides everything: alternation has the lowest precedence of all regex operators. This lesson shows what that means and how to avoid the classic mistakes.

Choosing between options

Node.js Basic alternation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The engine tries the alternatives left to right at each position and takes the first one that lets the whole pattern succeed. That ordering matters, as you will see below.

Precedence: what | splits

| splits the whole pattern (or the whole group it sits in). So ^cat|dog$ is not "the string is either cat or dog". It is "starts with cat" OR "ends with dog".

Node.js The anchor trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fix is parentheses: ^(cat|dog)$ limits the alternation to the group, and the anchors apply to the result.

flowchart TD
  subgraph W["/^cat|dog$/"]
    W1["^cat"] --- W2["dog$"]
  end
  subgraph R["/^(cat|dog)$/"]
    R1["^"] --> R2["cat or dog"] --> R3["$"]
  end

Without the group, the pipe separates two complete branches. With the group, it only chooses inside it.

Alternation inside part of a pattern

Grouping also lets you share a common prefix or suffix.

Node.js Factor out the common part

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For a choice between single characters, a class [ae] is shorter and faster than (a|e). Use alternation for longer words or whole sub-patterns.

Order matters

At each position the engine picks the first alternative that works. If one alternative is a prefix of another, put the longer one first.

Node.js Longer alternatives first

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the last line the \b after the group forces the engine to reject 1 and 10 (they are followed by more digits) and keep trying, which ends at 100. It works, but the clearer habit is to order alternatives from longest to shortest.

Empty alternatives

An alternative can be empty, which makes the group optional.

Node.js Empty alternative

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You will almost always prefer ? for optional pieces. A stray empty alternative like (a|b|) is often an accident that makes the pattern match everything, so treat it as a smell.

Non-capturing groups for alternatives

A normal group ( ) also captures the text it matched, which costs a little time and shifts group numbers. When you only want grouping, use a non-capturing group (?: ).

Node.js Capturing versus non-capturing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Captures are the topic of the next chapters; for now, remember (?:...) as "group without remembering".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does /^cat|dog$/ mean?

    | has the lowest precedence, so the pattern splits into ^cat and dog$.
  2. 2. Which pattern accepts only cat or dog as the whole string?

    Putting the alternation in a group scopes the pipe, so both anchors apply.
  3. 3. What does 'category'.match(/cat|category/)[0] return?

    The engine takes the first alternative that matches at the current position, so the shorter cat wins.
  4. 4. When is a character class better than alternation?

    [ae] is shorter and faster than (a|e) for single-character choices.

Summary

  • | means or; the engine tries alternatives left to right and takes the first one that works.
  • Alternation has the lowest precedence: group it with ( ) or (?: ) to limit its reach.
  • Order longer alternatives before shorter ones that share a prefix.
  • Use [ae] for single characters and ? for optional parts.

Next: Escape Sequences and Unicode Text