string.gsub()
The string.gsub()
function searches for occurrences of a pattern in a string and replaces them with a specified replacement. It is versatile and can perform global replacements or limit them to a specified number.
Syntax
string.gsub(s, pattern, replacement [, n])
Parameters
- Name
s
- Type
- string
- Description
The input string where replacements will be performed.
- Name
pattern
- Type
- string
- Description
The Lua pattern to match substrings in the string.
- Name
replacement
- Type
- string/function/table
- Description
The replacement for matched substrings. Can be:
- A string to substitute for each match.
- A function that returns the replacement dynamically based on the match.
- A table where the replacement is determined by the matched substring as the key.
- Name
n
- Type
- number (optional)
- Description
The maximum number of replacements to perform. Defaults to unlimited.
Return Value
Returns two values:
- The modified string with replacements applied.
- The number of replacements made.
Examples
Example 1: Basic Replacement
Replace all occurrences of a word in a string.
Example 1
local text = "Hello world, welcome to the Lua world."
local result, count = string.gsub(text, "world", "universe")
print(result) -- Output: Hello universe, welcome to the Lua universe.
print(count) -- Output: 2
Example 2: Limit the Number of Replacements
Replace only the first occurrence of a pattern.
Example 2
local text = "cat, cat, cat"
local result, count = string.gsub(text, "cat", "dog", 1)
print(result) -- Output: dog, cat, cat
print(count) -- Output: 1
Example 3: Use a Function for Replacement
Generate replacements dynamically with a function.
Example 3
local text = "a1 b2 c3"
local result = string.gsub(text, "%a%d", function(match)
return "[" .. match .. "]"
end)
print(result) -- Output: [a1] [b2] [c3]
Example 4: Use a Table for Replacement
Map replacements with a table.
Example 4
local text = "red, green, blue"
local colorMap = {
red = "rosso",
green = "verde",
blue = "blu",
}
local result = string.gsub(text, "%w+", colorMap)
print(result) -- Output: rosso, verde, blu
Example 5: Replace Patterns with Captures
Use captures in the replacement string.
Example 5
local text = "apple:10, banana:20, cherry:30"
local result = string.gsub(text, "(%w+):(%d+)", "%1 (%2)")
print(result) -- Output: apple (10), banana (20), cherry (30)
Use Cases
- Search and Replace: Modify strings by replacing specific patterns.
- Dynamic Replacements: Perform complex replacements using functions or tables.
- Formatting: Adjust string content, such as inserting or modifying data formats.
See also
string.find()
: Locates patterns in a string without replacing them.string.match()
: Extracts specific substrings matching a pattern.string.gmatch()
: Iterates over all occurrences of a pattern in a string, often used before applyingstring.gsub()
for more control.