Substitutes text matching a pattern with a replacement.
text, count = string.gsub(s, pattern, replace [, n])
= gsub
= s:gsub
Arguments
- s
- string - String to search.
- pattern
- string - Pattern matching expression, covered in HOWTO: Use Pattern Matching or the Patterns Tutorial on Lua-Users.org.
- replace
- string|function|table - Replacement text, or a function which may return replacement text, or a lookup table which may contain replacements (see details).
- n
- number? - The maximum number of substitutions (unlimited if omitted).
Returns
- text
- string - Resulting string after any substitutions.
- count
- number - Number of times the pattern was matched; including when no suitable replacement was found (applicable when
replaceis a function or table).
Details
- For each match against
patternins, gsub replaces this matched text using either:- A string that may include captures such as
$1; - A function that receives captures as arguments and returns a string or nil to leave unchanged; or
- A table with keys to be replaced by values, or unchanged if the matched text is not a key.
- A string that may include captures such as
- When
nis defined, each match counts even if there is no change.
Example
Simple substitutions:
> = string.gsub("Hello banana", "banana", "Lua user")
Hello Lua user 1
> = string.gsub("banana", "a", "A", 2) -- limit substitutions made to 2
bAnAna 2
Simple substitutions with captures:
> = string.gsub("banana", "(an)", "%1-") -- capture any occurrences of "an" and replace with inserted trailing dashes
ban-an-a 2
> = string.gsub("banana", "a(n)", "a(%1)") -- place parentheses around each "n" which follows an "a"
ba(n)a(n)a 2
> = string.gsub("banana", "(a)(n)", "%2%1") -- reverse any occurrences of "an"
bnanaa 2
Using a function with captures:
> = string.gsub("Hello Lua user", "(%w+)", print) -- print any words found
Hello
Lua
user
3
> = string.gsub("Hello Lua user", "(%w+)", function(w) return string.len(w) end) -- replace each word with that word's length
5 3 4 3
> = string.gsub("banana", "(a)", string.upper) -- make all occurrences of "a" uppercase
bAnAnA 3
> = string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any occurrences of "an"
bnanaa 2
Using a table with keys/values:
> = string.gsub("HelloWorld!", "%w%w%w%w%w", {["World"] = "WorldOfWarcraft"}) -- Matches Hello and World (5 letters), but only World is in the table.
HelloWorldOfWarcraft 2