0Pricing
Lua Academy · Lesson

string.gsub and string.gmatch

Replace and iterate over pattern matches in strings.

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]

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