Lua patterns aren’t Regex
The typical implementation of POSIX regexp would be larger than all the Lua standard libraries put together, so they wrote their own, simpler thing
Quick one this week—
One weird Lua tidbit is that Lua has its own pattern matching syntax that isn’t regex or globbing but a secret, third thing.
Unlike several other scripting languages, Lua does not use POSIX regular expressions (regexp) for pattern matching. The main reason for this is size: A typical implementation of POSIX regexp takes more than 4,000 lines of code. This is bigger than all Lua standard libraries together. In comparison, the implementation of pattern matching in Lua has less than 500 lines. Of course, the pattern matching in Lua cannot do all that a full POSIX implementation does. Nevertheless, pattern matching in Lua is a powerful tool and includes some features that are difficult to match with standard POSIX implementations.
This mostly comes up in the string
library, in functions like string.find
, string.gsub
, and string.gfind.
The best general description I’ve found so far of how to use Lua patterns is in documentation for, of all things, Garry’s Mod. The official Lua docs are also pretty good.
The big giveaway that you’re looking at a Lua pattern rather than a regex will generally be that you’ll see a lot of %
and few or no /
.