liveBook · Manning

Regular expression

As explained in Build a Reasoning Model (From Scratch)

A pattern-matching technique for searching and extracting text using formal expression syntax.

A regular expression (regex) searches response text for structured patterns. In answer extraction, it recognizes numeric candidates such as fractions, decimals, and scientific notation when a final boxed answer is unavailable. section 3.4

Use regex-based extraction alongside boxed-answer parsing:

  • Compile a numeric pattern with Python’s re library. section 3.4
  • Search the full response and select the last matching number. section 3.4
  • Apply fallback policies such as number_then_full, number_only, or none. section 3.4

Extracting a final numeric candidate

Given response text containing “abc < > 14/3 abc” and no boxed answer, the regex finds 14/3 as the final candidate. A boxed value such as \boxed{14/3} takes precedence. section 3.4

Listing 3.5 Extracting the final answer candidate
import re

RE_NUMBER = re.compile(  #1
    r"-?(?:\d+/\d+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)"
)

def extract_final_candidate(text, fallback="number_then_full"):

    result = ""  #2

    if text:  #3
        boxed = get_last_boxed(text.strip())
        if boxed:
            result = boxed.strip().strip("$ ")

        elif fallback in ("number_then_full", "number_only"):#4
            m = RE_NUMBER.findall(text)
            if m:
                result = m[-1]  #5
            elif fallback == "number_then_full":

                result = text  #6
    return result

Inspect the compiled numeric pattern and fallback implementation used to extract the final candidate. section 3.4

How Build a Reasoning Model (From Scratch) covers it

How deep it goes
Defines regex as pattern search and applies one numeric pattern, without explaining regex syntax in detail.
Examples
Demonstrates fractions, boxed candidates, missing boxes, whitespace, punctuation, and final-number selection.
What it assumes
Assumes answer-box extraction and model response text while deferring detailed regex syntax.
What you can do after
Apply it via Python’s re library to find numeric fallback candidates in generated answer text.
How it connects
Connects regular expressions to Python’s re library, boxed-answer extraction, fallback policies, and answer normalization.

Also explained in

Compare how 27 books explain regular expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Reasoning Model (From Scratch). The section links point to the parts of the book it draws on.