string.gsub and string.gmatch
Replace and iterate over pattern matches in strings.
string.gsub and string.gmatch is a free Lua Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
string.gsub Basics
string.gsub(s, pattern, repl, n) replaces matches of pattern in s with repl, up to n times (default: all). It returns the resulting string and the number of replacements made. The replacement can be a string, table, or function.
local s = "hello world hello"
local result, count = string.gsub(s, "hello", "hi")
print(result) -- hi world hi
print(count) -- 2
-- Limit replacements
local r2 = string.gsub(s, "hello", "hi", 1)
print(r2) -- hi world helloCapture References in Replacement
In the replacement string, %1, %2, etc. refer to captures in the pattern. %0 refers to the entire match. Use this to rearrange or wrap matched text.
-- Swap first and last name
local name = "Smith, John"
local swapped = string.gsub(name, "(%a+), (%a+)", "%2 %1")
print(swapped) -- John Smith
-- Wrap numbers in brackets
local text = "items: 3 and 7 total 10"
local tagged = string.gsub(text, "%d+", "[%0]")
print(tagged) -- items: [3] and [7] total [10]Function as Replacement
When the replacement is a function, gsub calls it with each match (or captures) and uses the return value as the replacement. Return nil or false to keep the original match. This enables dynamic, computed replacements.
local env = {NAME="Lua", VERSION="5.4"}
local template = "Welcome to $NAME version $VERSION!"
local result = string.gsub(template, "%$(%w+)", env)
print(result) -- Welcome to Lua version 5.4!
-- Double each number
local s = "a1 b2 c3"
local r = string.gsub(s, "%d+", function(n)
return tostring(tonumber(n) * 2)
end)
print(r) -- a2 b4 c6Table as Replacement
When the replacement is a table, gsub looks up each match (or first capture) in the table and uses the result. If the lookup returns nil or false, the original match is kept. This is perfect for substitution dictionaries.
local abbreviations = {
str = "string",
num = "number",
tbl = "table",
fn = "function",
}
local text = "A str can hold a num or a tbl"
local expanded = string.gsub(text, "%a+", abbreviations)
print(expanded)
-- A string can hold a number or a tablestring.gmatch Basics
string.gmatch(s, pattern) returns an iterator over all matches of pattern in s. Each call to the iterator returns the next match (or captures if the pattern has them). It's the idiomatic way to iterate over matches in Lua.
local s = "one=1 two=2 three=3"
-- Iterate all words
for word in string.gmatch(s, "%a+") do
io.write(word .. " ")
end
print() -- one two three
-- Iterate key=value pairs
for k, v in string.gmatch(s, "(%a+)=(%d+)") do
print(k, v)
endTokenizing with gmatch
Use string.gmatch to tokenize input: split by whitespace, parse CSV rows, or extract structured data. The pattern defines what to capture; everything else is treated as a separator.
-- Split by whitespace
local function tokenize(s)
local tokens = {}
for token in string.gmatch(s, "%S+") do
tokens[#tokens+1] = token
end
return tokens
end
local toks = tokenize(" hello world lua ")
for i, t in ipairs(toks) do
print(i, t)
end
-- 1 hello 2 world 3 luaURL Parameter Parsing
Parse query strings by iterating key-value pairs. The pattern ([^&=]+)=([^&]+) captures each key and value separated by =, between & delimiters.
local url_params = "name=Alice&age=30&city=Istanbul"
local params = {}
for key, value in string.gmatch(url_params, "([^&=]+)=([^&]*)") do
params[key] = value
end
print(params.name) -- Alice
print(params.age) -- 30
print(params.city) -- IstanbulStripping HTML Tags
A common text processing task: remove HTML tags from a string. Use string.gsub with a pattern that matches opening and closing tags, replacing them with empty string.
local html = "<h1>Hello</h1> <p>World <b>bold</b></p>"
local plain = string.gsub(html, "<[^>]+>", "")
print(plain) -- Hello World bold
-- Replace <br> with newline
local html2 = "line1<br>line2<br/>line3"
local fixed = string.gsub(html2, "<br/?>", "\n")
print(fixed)Escaping Magic Characters
Lua pattern magic characters are: . + * ? [ ] ^ $ % ( ). To match them literally, escape with %. When using plain strings with these characters, pass true as the fourth argument to string.find to disable pattern matching.
-- Escape a string for use in a pattern
local function escapePattern(s)
return (string.gsub(s, "[%(%)%.%%%+%-%*%?%[%^%$]", "%%%1"))
end
local query = "1+1=2"
local pattern = escapePattern(query)
print(string.find("result: 1+1=2", pattern, 1)) -- 9 13Count Occurrences
Use the second return value of string.gsub (replacement count) to count pattern occurrences in a string, even without making any replacement.
local text = "banana"
local _, count = string.gsub(text, "a", "")
print("'a' appears " .. count .. " times") -- 3
-- Count words
local sentence = "the quick brown fox"
local _, wordCount = string.gsub(sentence, "%S+", "")
print("Words:", wordCount) -- 4Quick Check
What does string.gsub("hello", "l", "L") return?
Recap: gsub and gmatch
Summary:
gsub(s, pat, repl, n)— replace; repl can be string/table/function%1...%nin replacement strings reference capturesgmatch(s, pat)— iterate all matches- Use
%to escape magic pattern chars:%.%+etc. - Count occurrences: second return value of gsub
Frequently asked questions
Is the “string.gsub and string.gmatch” lesson free?
Yes — the full text of “string.gsub and string.gmatch” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “string.gsub and string.gmatch”?
Replace and iterate over pattern matches in strings. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “string.gsub and string.gmatch” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- String Basics: Concat and Length
- Finding and Extracting Substrings
- string.format for Output
- string.gsub and string.gmatch