Keep Regex Extracts Connected to Their Original Match Spans

Retain regex match spans with extracted research text, identify the source and coordinate units, and inspect how text edits invalidate earlier positions.

Regex match objects and source-coordinate spans, distinct from full structured-document parsing or a general annotation bookmark.

Substantively revised October 21, 2026. Author interpretation, documented cases and hypothetical examples are distinguished below.

Two extracted strings can be identical and belong to different places in the source. A table containing 12 ms twice does not explain which occurrence supported which record. Retaining a match's location turns an isolated value into an inspectable extraction, provided the location names the correct source and coordinate system.

Direct answer

Use match objects when extraction needs positions, and retain the source reference, pattern, flags, full match and relevant group spans. Distinguish a group's span from the whole match and a substring's local coordinates from the original text's coordinates. Verify that slicing the named source at the recorded boundaries reproduces the matched text. A regex match is a candidate selected by a pattern, not automatic validation of a measurement or the source's meaning. Record the actual engine and scope rather than assuming another language interprets the pattern identically.

Key takeaways

Matched value and matched occurrence are different information. Repeated values can be legitimate separate occurrences. A value-only export loses the direct positional evidence needed to inspect those occurrences without reconstructing the extraction from other artifacts.

The source coordinate system is part of the result. A search starting at position twelve in the original string differs from a search over a new string sliced from that position. Both can find the same text while reporting different indices relative to their actual input.

Pattern success is narrower than semantic correctness. The controlled expression below can find the tail 5 ms inside 12.5 ms. That false-positive control is a reason to review the intended grammar, not to promote a convenient substring extractor into a general quantity validator.

Definitions and relationships

A full match is the substring selected by the complete regular expression for one occurrence. A capturing group selects a subpart of that occurrence. The group's start and end can differ from the full match's boundaries, even when both results are used in one extracted record.

A span supplies start and end indices for the relevant substring. The indices are meaningful relative to the input object and its indexing convention. In the experiment, Python str positions are used with Python string slicing; they are not byte offsets or a claim about another engine's coordinates.

A pattern and its flags define the selected matching operation. Search, match and fullmatch impose different conditions on the input. Retaining only the resulting value hides those choices and makes it harder to determine whether a later disagreement concerns source changes, pattern behavior or an incorrect interpretation of the match.

The problem with a value-only extraction table

Imagine a hypothetical researcher scanning an authorized text log for candidate duration tokens. The extraction writes numbers and units into a table. Two rows contain the same value, and a reviewer asks whether the second is a duplicate record or a separate occurrence in the log.

The value-only table cannot answer that question by itself. It represents the characters selected but not the source locations from which they came. Removing one repeated value could therefore discard a legitimate occurrence, while keeping both without inspection could preserve a duplicated processing result.

The practical question is what evidence makes the extraction reversible enough to inspect. A source reference, pattern and match spans give the reviewer a route back to the actual substring. They do not establish that the surrounding sentence is true or that the token means the quantity the analyst intends.

Root cause: extracted values are detached from the matching operation

Convenient extraction functions often return strings or group tuples directly. Those outputs are useful when positions do not matter. The blind spot appears when a workflow later needs positional evidence but has treated the convenient return type as a complete extraction record.

Capturing groups can make the loss less visible. A returned number and unit look analytically useful, but they no longer show the exact full substring or its boundaries. A reviewer may assume the pattern validated an entire field when it only found a fragment somewhere within a longer string.

The repair is to retain evidence at the match-object boundary before reducing it to analysis columns. Record the actual operation and source coordinates, then derive the convenient values. This separates what the engine selected from the substantive decision about whether that selection is an acceptable research observation.

Framework: the Match-to-Source Contract

The Match-to-Source Contract is the author's proposed inspection method. Its components are Pattern Basis, Occurrence Boundary, Group Meaning and Coordinate Origin. It makes a particular extraction explainable rather than promising that one regular expression can parse every relevant document or validate every numerical claim.

Pattern Basis records the expression, flags and engine used. Specify whether it searches for candidates or validates a whole field. A successful search through a longer sentence is not evidence that every character in that sentence satisfies the pattern's grammar.

Occurrence Boundary retains the full matched substring and its span in the actual input. Use the boundaries to reproduce the substring by slicing that same source representation. Distinguish repeated equal strings by their occurrences instead of deduplicating them solely because their values match.

Group Meaning records which captured group supplies each derived field. A numerical group can exclude the unit that belongs to the full match. Keep enough boundaries to show whether a downstream value came from the whole occurrence or only a selected subpart.

Coordinate Origin identifies the source and any window used for matching. A position parameter on the original string and a separately sliced substring produce coordinates relative to different inputs. If a slice is used, retain its origin explicitly before presenting local positions as though they addressed the original text.

Applying the contract to candidate duration tokens

Start with an authorized retained text and state the narrow token syntax being sought. The experiment uses digit characters from zero through nine, one space and the unit ms followed by a word boundary. It is intentionally a candidate extractor, not a complete grammar for quantities in prose.

Use match objects to collect the full occurrence, the named value and unit groups, and their spans. Verify full and group slices against the same source. Keep the source unchanged during the check so the coordinates have a defined interpretation.

Then review candidates against the actual analytical requirement. Include a decimal counterexample or other boundary input that can expose an incomplete pattern. A location-preserving extraction makes a false positive easier to inspect; it does not make that false positive a valid observation merely because its provenance is well recorded.

Documented example: match objects expose position evidence

Python's re documentation describes finditer as yielding match objects and documents full-match and group start, end and span access. Its slicing relationship connects a recorded group span with the substring selected from the match's input. [S1]

This provides a concrete inspection route rather than a vague instruction to retain context. The experiment checks that source[start:end] equals the matched text for each candidate and separately checks the captured numerical group. The two boundaries are not assumed to be identical.

The API reference is versioned to Python 3.11, while the actual runtime is recorded as 3.11.9. The article makes no claim that these exact patterns, group syntax or coordinate conventions transfer unchanged to every programming language or database regex interface.

Documented example: matching choices affect the selected extent

Python's Regular Expression HOWTO distinguishes matching operations and explains greedy and nongreedy repetition with concrete examples. These mechanisms show why a pattern's selected extent needs inspection rather than confidence based only on the presence of desired words. [S2]

The local bracket fixture makes this visible: a greedy expression selects both bracketed groups as one candidate, while the selected nongreedy expression returns two in that simple input. That result is not a general parser for nested brackets or structured markup.

The useful review question is what the expression actually recognizes and how its operation is bounded. The HOWTO's discussion does not authorize extending a small extraction pattern into full HTML or XML parsing. Those tasks require representations and processing appropriate to their structure.

Documented example: Unicode support needs a stated scope

Unicode Technical Standard 18 discusses levels and details of Unicode regular-expression support. The consulted revision is 25, dated 16 January 2025. Its existence is not a certificate that Python's standard re module satisfies every level or user expectation described there. [S3]

The experiment separately checks one selected digit-class distinction: a Unicode digit shorthand matches an Arabic-Indic digit in the Python str control, while the ASCII flag restricts that selected class. This demonstrates why flags and character assumptions belong in the extraction record.

It does not establish comprehensive multilingual tokenization, grapheme segmentation or cross-engine equivalence. A shorthand's familiar name can conceal a scope decision. Check the relevant engine and input rather than assuming that digit or word means exactly the same set of characters everywhere.

Case study: three candidates and two equal strings

The author used the invented source Log: 12 ms; 8 ms; repeat 12 ms. The expression contained named groups for the digit sequence and the unit. Python 3.11.9 returned three nonoverlapping match objects from the source, in its scan order.

The full spans were 5–10, 12–16 and 25–30, interpreted as start included and end excluded for the tested Python slices. The numerical group spans were 5–7, 12–13 and 25–27. The units occupied their own group spans, so a number-only field did not describe the full matched extent.

The first and third full matches both contained 12 ms, yet their spans differed. The experiment confirmed their source slices individually. Those equal strings therefore represented different source occurrences in the specimen, not evidence that one row should automatically be removed.

Calling findall with the capturing groups returned value-and-unit tuples for the same source. That output was convenient for derived fields, but it did not carry the explicit span evidence present in the match objects. The experiment compares the representations rather than declaring one API universally preferable for every task.

Original-window positions differ from sliced positions

The next control began searching at source position twelve. Running the compiled pattern over the original string with that position returned the 8 ms candidate at span 12–16. Its coordinates still referred to the original input object.

Searching a separate string formed by slicing from position twelve found the same text at local span 0–4. Adding the retained slice origin, twelve, reconstructed the original span in this controlled case. Without that origin, a saved local index could point to the wrong part of the original log.

This is a coordinate-accounting problem, not a new text-anchoring guarantee. The exercise does not relocate excerpts across changed source versions or browser documents. It makes the current extraction's actual input and origin explicit so a reviewer can interpret its reported positions correctly.

What the twenty-nine assertions establish

The report records twenty-nine passing assertions on invented Python strings. They cover full and group spans, exact source slicing, retained input references, equal-value occurrences, group tuples, matching operations, original versus sliced windows, greedy brackets, one digit-class distinction and a decimal false-positive control.

The prefixed log produces no result from match at the start, while search finds the first candidate at position five. Fullmatch rejects the whole log and accepts the isolated token 12 ms. These outcomes distinguish finding a fragment from validating an entire supplied input.

There is no performance benchmark, security assessment, comprehensive quantity recognizer, structured-document parser, browser test or UTS 18 conformance result. The assertions establish the selected engine's behavior and the recorded match-to-source relationships for the fixtures. Substantive acceptance of a candidate remains another decision.

Failure example: a decimal tail looks like a valid candidate

The narrow expression can search 12.5 ms and return 5 ms. Its matching rule sees a digit sequence, a space and the selected unit at that position. It has not validated the complete decimal quantity that a human reader may intend.

This is an intentionally exposed limitation, not a recommended parser for measurement fields. Retaining the span makes the selected fragment inspectable, but does not repair the recognition rule. A traceable false positive is still a false positive relative to a broader intended grammar.

The correction is to define and test that broader grammar or use a more suitable processing route. Include counterexamples that resemble valid candidates but should not be accepted. Do not let accurate position evidence turn a partial regex match into an unsupported claim of semantic validation.

Failure example: a group span is reported as the whole evidence

A hypothetical exporter stores the numerical group and its span, then labels that span as the complete duration expression. For the first fixture candidate, the group ends at seven while the full occurrence ends at ten. The unit and separating space are outside the recorded group.

The value can be useful, but the label is wrong. A reviewer attempting to reconstruct the full expression from that span retrieves only the number. The mismatch comes from conflating a derived field with the full occurrence from which it was extracted.

The correction is to name each boundary. Retain full-match evidence alongside the relevant group mapping, and derive analytical fields from those named groups. This keeps later users from inferring more source coverage than the stored coordinates actually identify.

Why pattern and flags belong with the result

An extracted string is the output of a particular recognition rule. Changing a character class, a matching operation or a flag can change which candidates appear without changing the source. A result that omits those inputs is harder to compare with a later extraction.

The selected digit control illustrates one such difference. A Unicode shorthand and its ASCII-restricted use do not return the same set on the invented mixed-digit string. Neither choice is inherently correct for every research task; the intended grammar determines which needs to be recognized.

Record the rule so a disagreement can be investigated. Do not treat the expression as a universal language-independent object, and do not attribute capabilities from a broad Unicode specification to an engine that has not been checked for them. The appropriate claim follows from the actual implementation and fixtures.

Common mistakes and specific corrections

The first mistake is deduplicating equal extracts without checking their occurrences. Compare source spans and processing history before discarding a repeated value. Identical characters can arise at separate positions with distinct evidential roles.

The second is saving a substring's local positions as original coordinates. Retain the slice origin or search the original input with an appropriate window. Verify the resulting source slice rather than trusting an unlabeled number.

The third is confusing search success with whole-field validation. Test match, search and fullmatch according to the question. A pattern that finds a token somewhere in a sentence has not thereby accepted the whole sentence's grammar or meaning.

The fourth is expanding a useful regex into every parsing task. Keep the token language narrow enough to explain and test. Structured documents, semantic measurement rules and complex multilingual processing can require other tools or additional evidence beyond the selected expression.

Counterargument: values are all the analysis needs

Some derived calculations legitimately require only values. Keeping match objects indefinitely may be unnecessary once an accepted extraction has been recorded elsewhere. The counterargument is strongest when another retained artifact supplies the source and interpretation evidence needed for review.

It is weaker when the value-only table is the sole surviving record. Repeated values, a false positive or a changed pattern can then be difficult to distinguish. A small provenance record can preserve the investigative route without forcing every downstream calculation to carry the full source text.

There is a tradeoff between compact analytical tables and inspectable extraction history. Keep the source reference and match evidence at the appropriate boundary, then derive simpler views deliberately. The method asks that reduction not erase the only evidence needed to evaluate the candidates later.

Action plan

Choose one authorized regex extraction and identify the actual input representation, engine, expression and flags. State whether it finds candidates or validates complete fields. Preserve the source needed to inspect the result.

Collect full matches and relevant group spans through the actual match interface. Confirm source-slice equality for selected examples, including repeated equal strings. If matching over substrings, record the origin needed to interpret local positions.

Add a counterexample exposing the pattern's recognition limits. Check a near-valid longer input, a greedy extent or a character-class boundary relevant to the task. A passing happy-path specimen does not establish the intended complete grammar.

Record which candidates were accepted after review and why. Keep their source relationship distinct from source truth or a wider conformance claim. The extraction is useful when its selected text, boundaries and limitations remain explainable enough for another person to inspect.

FAQ

Why keep spans when the extracted text is already stored?

They distinguish occurrences and provide a direct route back to the source substring. Equal extracted text can come from different source positions.

Is a capturing group's span always the full match?

No. The numeric group excludes the space and unit in the fixture. Record full and group boundaries according to what each field represents.

What were the three full spans in the log?

They were 5–10, 12–16 and 25–30 under Python string slicing. The two equal 12 ms strings occupy different occurrences.

What do these coordinates measure?

Indices into the actual Python str input used in the test. They are not advertised as byte offsets, browser positions or another language's indexing convention.

Does findall always return the whole match string?

Its result depends on capturing groups. The selected pattern returns group tuples, which are convenient values without the explicit positional fields retained by match objects.

Why does match fail on the prefixed log?

The selected token does not begin at the start of that input. Search finds it later, while fullmatch asks whether the entire supplied input matches.

Can fullmatch validate the entire log with this pattern?

Not in the fixture. It rejects the larger containing string while accepting the isolated 12 ms token. That distinction is part of the intended operation.

Why do sliced coordinates start at zero?

The sliced string is another input object with its own origin. Retain the original slice offset if its local spans must be mapped back to the source.

Does a greedy bracket pattern select one bracket group?

The selected greedy expression spans both groups in the simple fixture. The nongreedy control returns two, without claiming to parse arbitrary nested structures.

Is the candidate expression a complete quantity parser?

No. Its decimal control returns 5 ms from 12.5 ms, deliberately demonstrating a recognition limit that requires another acceptance decision.

Do Unicode digit shorthands always mean ASCII digits?

No. The selected Python str control includes an Arabic-Indic digit unless restricted by the ASCII flag. Record the intended character assumptions.

Does citing UTS 18 certify this engine?

No. The reference discusses Unicode regex support; the local tests do not establish every conformance level or comprehensive multilingual behavior.

Did these tests process real research measurements?

No. All strings are invented fixtures. There is no reported participant, customer, production extraction or factual measurement outcome.

Do source spans prove the extracted claim is true?

No. They identify where the engine selected text. Source reliability, meaning and analytical acceptance require separate evidence.

What should accompany an accepted extraction?

Keep the source reference, input representation, pattern and flags, full match and group spans, coordinate origin and reviewed limits. Derive simpler analytical fields without discarding their investigative basis.

Recommended books

Mastering Regular Expressions, third edition, by Jeffrey E. F. Friedl, published by O'Reilly in August 2006, provides context on matching extent, engine differences and assumptions in text recognition. Current engine documentation and the recorded Python runtime govern the actual syntax and results used here.

Python Cookbook, third edition, by David Beazley and Brian K. Jones, published by O'Reilly in May 2013, offers practical context for text processing and retaining useful information from library interfaces. It is background for the extraction design, not evidence of the twenty-nine assertions.

Unicode Demystified by Richard Gillam, published by Addison-Wesley Professional in September 2002, supplies historical context on character representation. It should not be treated as current Unicode conformance evidence. The Match-to-Source Contract is the author's proposed method, distinct from either the book or UTS 18.

Further exploration

Inspect one value-only extraction and choose two equal results. Determine whether their source occurrences can still be distinguished and reconstructed. If the table cannot answer, locate the earlier artifact that retains the matching operation before inferring duplication.

Then test a boundary input that challenges the recognition rule. Accurate provenance and accurate recognition are separate achievements. A useful extraction retains enough evidence to inspect both instead of letting a plausible matched string stand for a conclusion the pattern never tested.

Primary evidence sources

Related concepts: systems thinking, wealth structure, and the survival loop. Read the editorial policy and citation guide.