Lua - String gsub() method



string.gsub() method is used to replace or substitute all or limited occurences of matching string as per given pattern. We can replace a string with string, table or even with function. string.gsub returns the substituted string as a result.

Syntax

string.gsub(s, pattern, replacement [, n])

Where −

  • s − is the string to be searched in.

  • pattern − pattern to match. We can use specialized characters, quantifiers and capture groups in the pattern.

  • replacement

    • string − A replacement string. Specialized characters like %1, %2 can be used for captures, %0 for whole word matching, %% can be used to match % and so on.

    • table − it is queried for every match considering the first capture as the key. If pattern is not having any capture, entire match is treated as a key of the table.

    • function − it is called for every match, while captured strings are passed as argument. This function should return either the replacement string or nil.

  • n − An optional field to limit the maximum number of substitutions to be done. If not present, all substitutions are done.

Returns

string.gsub() method returns two values, first, the substituted string and second, the number of times, substitution is done.

Example - Usage of string.gsub() function

In this example, we're changing the date format.

main.lua

local date = "2025/05/02"

-- Change date format using capture groups
local updated_date, count = string.gsub(date, "(%d+)/(%d+)/(%d+)", "%3-%2-%1")

-- prints Date: 02-05-2025 Count: 1
print("Date:", updated_date, "Count:", count)

Output

When we run the above program, we will get the following output−

local date = "2025/05/02"

-- Change date format using capture groups
local updated_date, count = string.gsub(date, "(%d+)/(%d+)/(%d+)", "%3-%2-%1")

-- prints Date: 02-05-2025 Count: 1
print("Date:", updated_date, "Count:", count)

Example - Using table with string.gsub() function

main.lua

local data = "The quick brown fox jumps over the lazy dog."

-- Replace words as per table
local substitutions = { ["quick"] = "fast",
   ["lazy"] = "energetic"
}
local updated_data, count = string.gsub(data, "(%w+)", substitutions)
print("Using table replacement:", updated_data, "Count:", count)

Output

When we run the above program, we will get the following output−

Using table replacement:        The fast brown fox jumps over the energetic dog.        Count:  9

Example - Using function with string.gsub() function

main.lua

local data ="Welcome to Lua!"

-- Replace words as per a function
local function reverseWord(word)
   return string.reverse(word)
end
local reversed, count = string.gsub(data, "(%w+)", reverseWord)
print("Function replacement:", reversed, "Count:", count)

Output

When we run the above program, we will get the following output−

Function replacement:   emocleW ot auL! Count:  3
Advertisements