Lua Academy · Lesson

string.gsub and string.gmatch

Replace and iterate over pattern matches in strings.

Lesson 4 of 412 steps

string.gsub and string.gmatch is a free Lua Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

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 hello

Capture 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 c6

Table 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 table

string.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)
end

Tokenizing 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 lua

URL 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)  -- Istanbul

Stripping 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  13

Count 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)  -- 4

Quick 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...%n in replacement strings reference captures
  • gmatch(s, pat) — iterate all matches
  • Use % to escape magic pattern chars: %. %+ etc.
  • Count occurrences: second return value of gsub
Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “string.gsub and string.gmatch” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “string.gsub and string.gmatch”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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

  1. String Basics: Concat and Length
  2. Finding and Extracting Substrings
  3. string.format for Output
  4. string.gsub and string.gmatch
← Back to Lua Academy