API gsub

Substitutes text matching a pattern with a replacement. text, count = string.gsub(s, pattern, replace [, n]) text, count = gsub(s, pattern, replace [, n]) text, count = (""):gsub(pattern, replace [, n])

Arguments

 * s : - String to search.
 * pattern : - Pattern matching expression, covered in HOWTO: Use Pattern Matching or the Patterns Tutorial on Lua-Users.org.
 * replace : || - Replacement text, or a function which may return replacement text, or a lookup table which may contain replacements (see details).
 * n : - The maximum number of substitutions (unlimited if omitted).

Returns

 * text : - Resulting string after any substitutions.
 * count : - Number of times the pattern was matched; including when no suitable replacement was found (applicable when   is a function or table).

Details

 * For each match against  in , gsub replaces this matched text using either:
 * A that may include captures such as  ;
 * A that receives captures as arguments and returns a string or nil to leave unchanged; or
 * A with keys to be replaced by values, or unchanged if the matched text is not a key.
 * When  is defined, each match counts even if there is no change.

Examples
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