Build your own regex engine
Stage 6 of 8v3 · 4bd8ec77

Captures

Record the text and boundaries of every group during backtracking.

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.

Capture Groups

Parentheses also capture matching substrings for extraction.

Mental Model: Indexed Capture Vectors

Groups index by the position of their opening parenthesis:

  • (a+)(b) over "zaaab":
    • Total span: [1, 5] ("aaab").
    • Group 1: "aaa".
    • Group 2: "b".
    • groups: ["aaa", "b"].

Your Goal in this Stage

Record substrings matched by each parenthesized group in groups.

Input Format

json
{
  "op": "search",
  "pattern": "(a+)(b)",
  "text": "zaaab"
}

Output Format

json
{
  "matched": true,
  "span": [1, 5],
  "groups": ["aaa", "b"]
}

Step-by-Step Implementation Guide

  1. Record group bounds: Store start/end indices upon entering and leaving parens.
  2. Extract slices: Slice captured substrings.
  3. Emit output: Print JSON with groups.

Acceptance Criteria

  • ✅ Captures text within parentheses.
  • ✅ Orders captures by opening parenthesis.

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.

An optional group that does not participate is null in groups. A participating group capturing zero characters is "". Number groups by opening parenthesis, including nested groups; repeated groups retain their last capture. Spans have an inclusive start and exclusive end.