Build your own regex engine
Stage 4 of 8v2 · 8320f6f9

Alternation

Build alternatives with lower precedence than concatenation.

Build it in your language

The tester treats your program as a black box: any language works. These are just the most convenient ones for this project.

Alternation Operator (|)

The pipe operator | defines alternative branches (cat|dog), succeeding if either branch matches.

Mental Model: Branch Evaluation

  1. Try branch A at the current offset.
  2. If it succeeds, return the match.
  3. If it fails, backtrack and evaluate branch B from the same offset.

Your Goal in this Stage

Support alternation with | in op: "search".

Input Format

json
{
  "op": "search",
  "pattern": "cat|dog",
  "text": "a dog"
}

Output Format

json
{
  "matched": true,
  "span": [2, 5]
}

Step-by-Step Implementation Guide

  1. Split pattern: Separate expressions by unescaped pipe |.
  2. Evaluate branches in order: Return on first matching alternative.
  3. Emit output: Print JSON with matched and span.

Acceptance Criteria

  • ✅ Dispatches correctly across alternative branches.
  • ✅ Reports valid span for successful branch.

Output and errors

Multiline examples are formatted for readability. Emit compact JSON without optional spaces, with properties in the order shown by the output examples, and a final newline. Keep logs off stdout. Tests compare exact text. Invalid inputs use stderr containing error, empty stdout, and exit 1. Valid inputs exit 0. Serialize integer results as JSON integers.