Lua Pattern Matching: find, match, gmatch, gsub and Captures
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.
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
Parentheses create captures. %1 through %9 can refer to captures in a replacement string:
| |
Iteration and balanced text
%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.