Skip to content

Text Processing

Regular expressions, text diffing, and semantic text splitting.

local text = require("text")
local re, err = text.regexp.compile("[0-9]+")
ParameterTypeDescription
patternstringRE2 compatible regex pattern

Returns: Regexp, error

local ok = re:match_string("abc123")
ParameterTypeDescription
sstringString to match

Returns: boolean

local match = re:find_string("abc123def")
ParameterTypeDescription
sstringString to search

Returns: string | nil

local matches = re:find_all_string("a1b2c3")
ParameterTypeDescription
sstringString to search

Returns: string[]

local match = re:find_string_submatch("user@example.com")
ParameterTypeDescription
sstringString to search

Returns: string[] | nil (full match + capture groups)

local matches = re:find_all_string_submatch("a=1 b=2")
ParameterTypeDescription
sstringString to search

Returns: string[][]

local pos = re:find_string_index("abc123")
ParameterTypeDescription
sstringString to search

Returns: table | nil ({start, end}, 1-based)

local positions = re:find_all_string_index("a1b2c3")
ParameterTypeDescription
sstringString to search

Returns: table[] | nil (nil when there are no matches)

local result = re:replace_all_string("a1b2", "X")
ParameterTypeDescription
sstringInput string
replstringReplacement string

Returns: string

local parts = re:split("a,b,c", -1)
ParameterTypeDescription
sstringString to split
nintegerMax parts, -1 for all

Returns: string[]

local count = re:num_subexp()

Returns: number

local names = re:subexp_names()

Returns: string[]

local pattern = re:string()

Returns: string

Compare text versions and generate patches. Based on go-diff (Google’s diff-match-patch).

local diff, err = text.diff.new()
local diff, err = text.diff.new(options)

Returns: Differ, error

FieldTypeDefaultDescription
diff_timeoutnumber1.0Timeout in seconds
diff_edit_costinteger4Cost of an empty edit
match_thresholdnumber0.5Match tolerance 0-1
match_distanceinteger1000Distance to search for match
patch_delete_thresholdnumber0.5Delete threshold
patch_margininteger4Context margin

Find differences between two texts. Returns an array of operations describing how to transform text1 into text2.

local diff, _ = text.diff.new()
local diffs, err = diff:compare("hello world", "hello there")
-- diffs contains:
-- {operation = "equal", text = "hello "}
-- {operation = "delete", text = "world"}
-- {operation = "insert", text = "there"}
ParameterTypeDescription
text1stringOriginal text
text2stringModified text

Returns: table, error (array of {operation, text})

Operations: "equal", "delete", "insert"

Count characters changed between versions.

local diffs, _ = diff:compare("hello world", "hello there")
local summary = diff:summarize(diffs)
-- summary.equals = 6 (characters unchanged)
-- summary.deletions = 5 (characters removed)
-- summary.insertions = 5 (characters added)
ParameterTypeDescription
diffstableDiff array from compare

Returns: table ({insertions, deletions, equals})

Format diff with ANSI colors for terminal display.

local formatted, err = diff:pretty_text(diffs)
print(formatted)
ParameterTypeDescription
diffstableDiff array from compare

Returns: string, error

Format diff as HTML with <del> and <ins> tags.

local html, err = diff:pretty_html(diffs)
-- Returns: "hello <del>world</del><ins>there</ins>"
ParameterTypeDescription
diffstableDiff array from compare

Returns: string, error

Generate patches that can be applied to transform one text into another. Patches can be serialized and applied later.

local text1 = "The quick brown fox jumps over the lazy dog"
local text2 = "The quick red fox jumps over the lazy cat"
local patches, err = diff:patch_make(text1, text2)
ParameterTypeDescription
text1stringOriginal text
text2stringModified text

Returns: table, error

Apply patches to transform text. Returns the result and whether all patches applied successfully.

local result, success = diff:patch_apply(patches, text1)
-- result = "The quick red fox jumps over the lazy cat"
-- success = true
ParameterTypeDescription
patchestablePatches from patch_make
textstringText to apply patches to

Returns: string, boolean

Split large documents into smaller chunks while preserving semantic boundaries. Based on langchaingo text splitter.

Splits text using a hierarchy of separators. First tries to split on double newlines (paragraphs), then single newlines, then spaces, then characters. Falls back to smaller separators when chunks exceed the size limit.

local splitter, err = text.splitter.recursive({
chunk_size = 1000,
chunk_overlap = 100
})
local long_text = "This is a long text that needs splitting..."
local chunks, err = splitter:split_text(long_text)
-- chunks = {"This is a long...", "...text that needs...", "...splitting..."}

Returns: Splitter, error

Options {id=“recursive-splitter-options”}

Section titled “Options {id=“recursive-splitter-options”}”
FieldTypeDefaultDescription
chunk_sizeinteger512Max characters per chunk
chunk_overlapinteger100Characters repeated between adjacent chunks
keep_separatorbooleanfalseKeep separators in output
separatorsstring[]nilCustom separator list

Splits markdown documents while respecting structure. Tries to keep headings with their content, code blocks intact, and table rows together.

local splitter, err = text.splitter.markdown({
chunk_size = 2000,
code_blocks = true,
heading_hierarchy = true
})
local readme = fs.read("README.md")
local chunks, err = splitter:split_text(readme)

Returns: Splitter, error

Options {id=“markdown-splitter-options”}

Section titled “Options {id=“markdown-splitter-options”}”
FieldTypeDefaultDescription
chunk_sizeinteger512Max characters per chunk
chunk_overlapinteger100Characters repeated between adjacent chunks
code_blocksbooleanfalseKeep code blocks together
reference_linksbooleanfalsePreserve reference links
heading_hierarchybooleanfalseRespect heading levels
join_table_rowsbooleanfalseKeep table rows together

Split a single document into an array of chunks.

local chunks, err = splitter:split_text(document)
for i, chunk in ipairs(chunks) do
-- Process each chunk (e.g., create embedding, send to LLM)
process(chunk)
end
ParameterTypeDescription
textstringText to split

Returns: string[], error

Split multiple documents while preserving their metadata. Each input document can produce multiple output chunks. All chunks inherit the metadata from their source document.

-- Input: pages from a PDF with page numbers
local pages = {
{content = "First page content...", metadata = {page = 1}},
{content = "Second page content...", metadata = {page = 2}}
}
local chunks, err = splitter:split_batch(pages)
-- Output: each chunk knows which page it came from
for _, chunk in ipairs(chunks) do
print("Page " .. chunk.metadata.page .. ": " .. chunk.content:sub(1, 50))
end
ParameterTypeDescription
pagestableArray of {content, metadata}

Returns: table, error (array of {content, metadata})

ConditionKindRetryable
Invalid pattern syntaxerrors.INVALIDno
Internal errorerrors.INTERNALno

See Error Handling for working with errors.