Standard POSIX or PCRE regular expression engines require hundreds of kilobytes of compiled code. To stay under 300 KB, Lua intentionally omits standard regex in favor of its own lightweight Pattern Matching Engine.
Core Character Classes
| Class | Matches |
|---|---|
%a | All letters (alphabetic) |
%c | All control characters |
%d | All digits (0-9) |
%l | All lowercase letters |
%u | All uppercase letters |
%s | All whitespace characters |
%w | All alphanumeric characters (letters + digits) |
%p | All punctuation characters |
%x | All hexadecimal digits |
Uppercase (%A, %D, etc.) | The complement (all non-matching characters) |
Magic Characters and Quantifiers
^: Anchor at start of string$: Anchor at end of string+: 1 or more repetitions (greedy)-: 0 or more repetitions (lazy / non-greedy)*: 0 or more repetitions (greedy)?: 0 or 1 occurrence%b(open)(close): Balanced match between paired characters (e.g.,%b()or%b{})
The Four Pattern Matching Functions
1. string.find
Returns the start and end indices of the match:
local str = "Hero health: 145/200"
local s, e = str:find("%d+/%d+")
print(str:sub(s, e)) -- "145/200"
2. string.match (Capture Extraction)
Parentheses create captures:
local logLine = "2024-04-15 [ERROR] Connection timed out on host 192.168.1.50"
local date, level, ip = logLine:match("(%d+%-%d+%-%d+)%s+%[(%a+)%].*host%s+(%d+%.%d+%.%d+%.%d+)")
print("Date: " .. date) -- 2024-04-15
print("Level: " .. level) -- ERROR
print("Host IP: " .. ip) -- 192.168.1.50
3. string.gmatch (Global Iterator)
Iterates over all matches in the text:
local queryParams = "name=valkyrie&level=99&guild=arcana"
for key, val in queryParams:gmatch("([^&=]+)=([^&=]+)") do
print(key .. " -> " .. val)
end
4. string.gsub (Global Substitution)
Replaces pattern matches with strings, tables, or functions:
local template = "Hello $name, your balance is $amt."
local data = { name = "Julian", amt = "$500" }
-- Pass table to gsub: matches are replaced by table lookups!
local rendered = template:gsub("%$(%a+)", data)
print(rendered) -- Hello Julian, your balance is $500.
Exercises
- Write a pattern validating email addresses matching
username@domain.tld. - Extract all HTML tags and their inner text from a markup string using
string.gmatch. - Use
%b()to parse nested mathematical parentheses expressions.