String Patterns Deep Dive
Lua doesn't have full regular expressions, instead it has a lighter-weight pattern system built into string.find, string.match, string.gmatch, and string.gsub. Patterns cover the vast majority of real-world text processing without needing a heavyweight regex engine.
Character classes
| Class | Matches |
|---|---|
%a | a letter |
%d | a digit |
%s | whitespace |
%w | a letter or digit |
%p | punctuation |
. | any character |
Uppercase versions (%A, %D, ...) match the complement. Quantifiers *, +, -, and ? work similarly to regex, though - is a lazy (shortest) repeat, unlike *'s greedy repeat.
Capturing groups
Parentheses in a pattern create a capture, string.match returns one value per capture (or the whole match if there are none).
Iterating all matches with gmatch
Search-and-replace with gsub
gsub returns two values: the new string, and how many replacements were made, don't forget the second one if you only want the string.
WARNING
Lua patterns are not regular expressions, features like alternation (a|b), non-capturing groups, and lookahead don't exist. For genuinely complex text processing, projects typically reach for a dedicated regex library instead of stretching patterns past what they're good at.