Lua Intermediate: OOP, Closures & Patterns

Lesson 3 of 5

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

ClassMatches
%aa letter
%da digit
%swhitespace
%wa letter or digit
%ppunctuation
.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

Lua

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

Lua

Search-and-replace with gsub

Lua

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.

📝 String Patterns Quiz

Passing score: 70%
  1. 1.Which character class matches a single digit in a Lua pattern?

  2. 2.string.gsub returns only the new string, never a replacement count.

  3. 3.Parentheses in a Lua pattern create a ____, which string.match returns as a separate value.