Replacing text with gsub
gsub replaces every match of a pattern and tells you how many replacements it made.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that gsub returns two values
- Using $1 instead of %1 for captures
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: