Iterating with string.gmatch()
Part of the Logic & Flow section of Coddy's Lua journey — lesson 39 of 54.
While string.match() finds the first occurrence of a pattern, what if you need to find all matches in a string? The string.gmatch() function solves this by returning an iterator that you can use in a for loop to process each match one by one.
The basic syntax looks like this:
for match in string.gmatch(text, pattern) do
-- process each match
endHere's an example that finds all numbers in a string:
local text = "I have 3 apples and 5 oranges"
for number in string.gmatch(text, "%d+") do
print(number)
end
-- Output:
-- 3
-- 5The pattern %d+ matches one or more digits, and the loop runs once for each number found.
You can also extract all words from a sentence:
local sentence = "Lua is a powerful language"
for word in string.gmatch(sentence, "%a+") do
print(word)
end
-- Output:
-- Lua
-- is
-- a
-- powerful
-- languageChallenge
EasyWrite a function extractHashtags that takes text and returns all hashtags found in the text, each on a separate line.
Use string.gmatch() to find all hashtags in the text. A hashtag starts with # followed by one or more letters.
Logic:
- Use
string.gmatch()with the pattern"#%a+"to find all hashtags - Iterate through each match and collect them
- Join all hashtags with newline characters (
\n) - If no hashtags are found, return an empty string
Parameters:
text(string): The text to search for hashtags
Returns: All hashtags found, each on a separate line. If no hashtags exist, return an empty string (string)
Cheat sheet
The string.gmatch() function returns an iterator that finds all occurrences of a pattern in a string, allowing you to process each match in a for loop.
Basic syntax:
for match in string.gmatch(text, pattern) do
-- process each match
endExample finding all numbers:
local text = "I have 3 apples and 5 oranges"
for number in string.gmatch(text, "%d+") do
print(number)
end
-- Output:
-- 3
-- 5Example extracting all words:
local sentence = "Lua is a powerful language"
for word in string.gmatch(sentence, "%a+") do
print(word)
end
-- Output:
-- Lua
-- is
-- a
-- powerful
-- languageTry it yourself
function extractHashtags(text)
-- Write code here
end
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet4Introduction to Metatables
What is a Metatable?setmetatable & getmetatableThe __index MetamethodThe __newindex MetamethodThe __tostring MetamethodArithmetic Metamethods Part 1Arithmetic Metamethods Part 2Recap - Read-Only Table7Advanced String Manipulation
string.gsub() for SubstitutionIntro to String Patternsstring.find()string.match()Iterating with string.gmatch()Recap - Log File Parser2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board