Lesson 46 of 55
9 mins readPython Pattern Search: string.find, match & gmatch
In Plain English
`string.find` returns start/end match indices, `string.match` extracts pattern captures, and `string.gmatch` returns an iterator over all occurrences in a string.
Deep Dive: How It Works
string.find(s, pat [, init [, plain]]): Returns start and end indices of match.
string.match(s, pat): Returns the captures defined in parentheses `(...)`.
string.gmatch(s, pat): Iterator yielding captures in a `for` loop.
Core Rules to Remember

string.find Indices: Returns start and end character positions.

string.gmatch Iterator: Traverses all occurrences across a multi-token string.
Live Interactive Example
Hit Run Code to see it liveExtracting Words and Pairs with gmatch
Python 3.12
1
2
3
4
5
6
Output Console
Click "Run Code" to view the rendered output.
How it works: gmatch extracted each pair and unpacked them into key and val.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Count Words with gmatch
Declare `local text = "Lua is fast and lightweight"`.
Count all words using `for w in text:gmatch("%a+") do count = count + 1 end`.
Print `"Word count: " .. count`.
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.