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 | local startIndex, endIndex = string.find("hello Lua", "Lua") |
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 | local key, value = string.match("color=blue", "^([%a_][%w_]*)=(.*)$") |
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 | for word in string.gmatch("one, two, three", "%a+") do |
%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.