← Back to Lua Course | Chapter 3: Strings | Lesson 6 of 7

Replacing text with gsub

gsub replaces every match of a pattern and tells you how many replacements it made.

In this page:

  1. Replacing text with gsub

Replacing text with gsub

string.gsub(s, pattern, repl, n) returns the new string and the number of replacements. The replacement can be a string, where %1 refers to the first capture, a table used as a lookup, or a function called for each match. The optional fourth argument limits the number of replacements.

Note: Wrap the call in parentheses to keep only the string, as in (s:gsub(a, b)).

Example: Replacing text with gsub

lua
local s = "hello world"
print(s:gsub("o", "0"))
print((s:gsub("(%w+)", "<%1>")))
print(s:gsub("%w+", string.upper, 1))
print(("$name is $age"):gsub("%$(%w+)", {name = "Ann", age = 30}))
print(("  trim me  "):gsub("^%s+", ""):gsub("%s+$", ""))

-- Output:
-- hell0 w0rld	2
-- <hello> <world>
-- HELLO world	1
-- Ann is 30	2
-- trim me	1
Common Mistakes
  1. Forgetting that gsub returns two values
  2. Using $1 instead of %1 for captures
  3. Expecting gsub to change the original string
Chapter Summary
  • gsub returns the string and a count
  • %1 refers to a capture
  • The replacement can be a table or function
  • The original string is unchanged

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.