liveBook · Manning

Regular expression

As explained in Data Analysis with LLMs

A regular expression is a pattern notation for matching and extracting substrings from text.

A regular expression is a pattern for matching and extracting the part of a text string that matters. In Python, re.findall returns matching substrings from an input string. section 4.3.3 section 5.2.5

A practical use is cleaning language-model output. If a generated answer places table data between <BeginTable> and <EndTable>, the pattern '<BeginTable>(.*)<EndTable>' extracts that table before rows and cells are split. section 4.3.3

Extracting a SQL query

When a generated answer surrounds SQL with ```sql and ```, the pattern '```sql(.*)```' finds the query. Python's re.DOTALL flag lets the dot match newlines, which may occur in a multiline query. section 5.2.5

import re

def post_process(raw_answer):
    table_text = re.findall(      #1
        '<BeginTable>(.*)<EndTable>', 
        raw_answer, re.DOTALL)[0]
    
    results = []
    for raw_row in table_text.split('\n'):  #2
        if raw_row:                    #3
            row = raw_row.split('|')
            row = [field.strip() for field in row]
            row = [field for field in row if field]
            results.append(row)
    return results

Shows a complete Python post-processing function that extracts marked table text, splits rows and cells, strips whitespace, and returns lists of values. section 4.3.3

Regular expressions also support simple filename searches:

  • Search filenames satisfying Joe*.png to find pictures associated with Joe. section 6.3.1

How Data Analysis with LLMs covers it

How deep it goes
Demonstrates pattern matching, re.findall, and re.DOTALL, but leaves missing-match robustness as a follow-up concern.
Examples
Uses table markers, SQL code fences, multiline queries, and tagged image filenames as concrete matching targets.
What it assumes
Assumes basic Python strings and functions while demonstrating how patterns, delimiters, and newline handling support extraction.
What you can do after
Apply it via Python's re.findall and re.DOTALL to extract marked content before parsing rows, cells, or queries.
How it connects
Connects regular expressions with text processing, Python, language models, prompts, SQL queries, and filename search.

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 Data Analysis with LLMs. The section links point to the parts of the book it draws on.