Lua.VM.Stdlib.Pattern (Lua v1.0.0-rc.2)

View Source

Lua 5.3 pattern matching engine.

Implements Lua's pattern language, which is NOT regex but a simpler custom syntax:

  • Character classes: %a (letters), %d (digits), %l (lowercase), %u (uppercase), %w (alphanumeric), %s (whitespace), %p (punctuation), %c (control), . (any)
  • Quantifiers: * (0+ greedy), + (1+ greedy), - (0+ lazy), ? (0 or 1)
  • Anchors: ^ (start), $ (end)
  • Sets: [abc], [^abc], [%a%d]
  • Captures: (pattern), %1-%9 backreferences
  • Balanced: %bxy
  • Escape: % + non-alphanumeric = literal

Summary

Functions

Compile a pattern string into a list of pattern elements. Returns {anchored, elements}.

Find first match of pattern in subject starting at position init (1-based). Returns {start, stop, captures} or :nomatch.

Global match - returns list of all matches as {start, stop, captures}.

Global substitution. Returns {result_string, count}.

Stateful global substitution. Returns {result_string, count, state}.

Match pattern against subject, returning captures or :nomatch.

Functions

compile(pattern)

Compile a pattern string into a list of pattern elements. Returns {anchored, elements}.

find(subject, pattern, init \\ 1)

Find first match of pattern in subject starting at position init (1-based). Returns {start, stop, captures} or :nomatch.

gmatch(subject, pattern)

Global match - returns list of all matches as {start, stop, captures}.

gsub(subject, pattern, repl, max_n \\ nil)

Global substitution. Returns {result_string, count}.

repl is one of: binary (string), function (arity 1, args -> result), or any other term (treated as a no-op, returning the whole match).

This entry point does NOT thread Lua VM state through the function replacement — any side effects in the callback (upvalue mutation, table writes) are dropped on the floor. For Lua-level string.gsub use gsub_stateful/5 instead.

gsub_stateful(subject, pattern, repl, state, max_n \\ nil)

Stateful global substitution. Returns {result_string, count, state}.

When repl is a function it must have arity 2 — (args, state) -> {result, state} — so callbacks that mutate Lua state (upvalues, tables) thread their changes back out. String and table replacements are state-pass-through.

match(subject, pattern, init \\ 1)

Match pattern against subject, returning captures or :nomatch.