Returns a string in which occurrences of a pattern are replaced. Alias for the standard library function string.gsub.


See also Lua library functions.

Signature:

newString, numMatched = gsub("s", "pattern", "rep" [, maxReplaced]) or gsub("s", "pattern", repTable [, maxReplaced]) or gsub("s", "pattern", repFunc [, maxReplaced])

Arguments:

  • s - A string (string)
  • pattern - A regular expression pattern (string, pattern)
  • rep - String with which to replace occurrences of pattern; may contain specifiers for numbered captures in the pattern (string)
  • repTable - Table containing replacement strings; replacements are looked up using captured substrings as keys, or the entire match if pattern specifies no captures (table)
  • repFunc - Function to supply replacement strings; called with captured substrings (or the entire match if pattern specifies no captures) as arguments (function)
  • maxReplaced - Maximum number of replacements to be made (number)

Returns:

  • newString - A copy of s in which occurrences of the pattern have been replaced as specified (string)
  • numMatched - Number of matches found (number)

Examples:

gsub("banana", "a", "A", 2)
-- returns "bAnAna", 2
gsub("banana", "(a)(n)", "%2%1")
-- returns "bnanaa", 2
gsub("banana", "[an]", {a="o",n="m"})
-- returns "bomomo", 5
gsub("banana", "(a)", strupper)
-- returns "bAnAnA", 3
This function is defined in the Lua standard libraries