Skip to content
everloot

Lore archive · Warcraft Wiki, 2023 dump

API gsub

Last wiki revision 2022-08-03

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

  • 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).
  • 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).
  • 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.

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

Source

https://warcraft.wiki.gg/wiki/API_gsub · retrieved 2023-11-13 · CC BY-SA 4.0

Converted from wikitext with templates, tables and images removed, so some sentences may be missing values.

This archive predates WoW: Forever. For collected gameplay facts see the Forever database. Search the archive.