Skip to content
Capture Groups
step 1/5

Reading — step 1 of 5

Read

~1 min readProduction Features

Capture Groups

(pattern) captures the substring matched by pattern for later retrieval.

python

Numbering: groups are numbered left-to-right by their opening parenthesis. Group 0 is always the whole match.

Named captures (Python (?P<name>...), JS (?<name>...)):

python

Implementation in NFA: each capture group adds two "save" pseudo-states:

  • One at the open paren — saves the current text position as group-N start
  • One at the close paren — saves the current text position as group-N end

When the simulation transitions through a "save" state, it does NOT consume input but updates the per-state save list. The accepting state's saves become the captures.

This adds O(N*K) overhead where K = number of groups. Still linear in text.

In backreferences \1, the engine compares the next text characters against the previously captured text — this is what makes them non-regular and forces backtracking.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…