Lesson 45 of 55
9 mins readPython Pattern Matching Classes & Magic Characters
In Plain English
Instead of standard PCRE regex, Lua features a lightweight **Pattern Matching Engine** (under 4KB). Patterns use `%` as an escape character and character classes like `%d` (digits) and `%a` (letters).
Deep Dive: How It Works
Character Classes: `%d` (digits), `%a` (letters), `%s` (spaces), `%w` (alphanumeric), `%p` (punctuation).
Uppercase Inversion: `%D` (non-digits), `%A` (non-letters), `%S` (non-spaces).
Quantifiers: `+` (1+), `*` (0+), `-` (non-greedy 0+), `?` (0 or 1).
Anchors: `^` (beginning of string), `$` (end of string).
Core Rules to Remember

% is the Escape Character: Lua uses `%` instead of `\` for pattern classes and escaping.

Minus (-) for Non-Greedy: `-` matches the shortest possible repetition.
Live Interactive Example
Hit Run Code to see it liveMatching Patterns in Lua
Python 3.12
1
2
3
4
5
6
7
8
Output Console
Click "Run Code" to view the rendered output.
How it works: (%d+) captured the digits, and (%a+) captured the status word.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Extract Port with Pattern
Declare `local str = "host:localhost port:8080"`.
Extract port with `local port = str:match("port:(%d+)")`.
Print `"Port: " .. port`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.