LUA / CHAPTER 07
Captures and literal-safe substitutions
IntermediateUse Lua patterns without importing regular-expression assumptions.
By the end of this chapter
- Anchor an entire structured value
- Read captures after a successful match
- Distinguish replacement text from callback results
The idea
Lua patterns provide character classes, repetition, anchors, and captures, but they are not a full regular-expression engine. Write a pattern from the exact accepted format and use start and end anchors when the whole string must match. Character classes such as [0-9] make an ASCII-only numeric field explicit. A failed match returns nil rather than a partially validated record.
String.gsub returns both transformed text and the number of replacements. Replacement strings interpret percent escapes, so arbitrary replacement data may require a function that returns the desired text literally. Keep extraction separate from numeric conversion and range checks: matching digits proves a shape, not that the quantity is meaningful for the application. Test trailing junk, missing fields, and repeated delimiters.
local label,digits=string.match("box:12","^([a-z]+):([0-9]+)$")
print(label)
print(tonumber(digits)+1)
local text,n=string.gsub("a-a","a",function() return "%" end)
print(text..":"..n)box 13 %-%:2
Captures separate the fields, and the replacement function supplies literal percent signs while gsub counts both changes.
Try it yourself
Parse label:count only when the entire string matches and the count is within a stated range.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING