Nanfeng

Notes on software development, code, and curious ideas

Pattern Matching in Lua

Lua patterns are a compact matching language used by string.find, string.match, string.gmatch, and string.gsub. They resemble regular expressions but have a smaller, different syntax.

1
2
3
local startIndex, endIndex = string.find("hello Lua", "Lua")
local digits = string.match("order=314", "%d+")
local clean = string.gsub("a b", "%s+", " ")

Character classes include %a for letters, %d for digits, %s for whitespace, %w for alphanumeric characters, and uppercase complements such as %D. Escape Lua pattern punctuation with %.

Captures

1
2
local key, value = string.match("color=blue", "^([%a_][%w_]*)=(.*)$")
print(key, value)

Parentheses create captures. %1 through %9 can refer to captures in a replacement string:

1
local swapped = string.gsub("Ada Lovelace", "(%a+)%s+(%a+)", "%2, %1")

Iteration and balanced text

1
2
3
4
5
for word in string.gmatch("one, two, three", "%a+") do
print(word)
end

local inside = string.match("call(a, b)", "%b()")

%b() matches balanced delimiters, and %f[...] is a frontier pattern useful at token boundaries. Quantifiers are +, *, - for non-greedy repetition, and ? for optional content.

Lua patterns cannot express every regular language feature and are not a full parser. For nested grammars, complex validation, or Unicode-aware text rules, use a parser or an appropriate pattern library. Also remember that built-in character classes generally operate on bytes and the current C locale, not Unicode grapheme clusters.

+