Wowpedia

We have moved to Warcraft Wiki. Click here for information and the new URL.

READ MORE

Wowpedia
m (Corrected spellings, standardized expected results format, corrected punctuation errors (mostly by eliminating the need for some punctuation)~~~~)
Tag: Visual edit
(Formatting, and adding the lookup table alternative.)
Tags: WoW API docs Source edit
Line 1: Line 1:
 
{{luaapi}}
 
{{luaapi}}
  +
Substitutes text matching a pattern with a replacement.
string.gsub(s, pattern, replace [, n])
 
gsub(s, pattern, replace [, n])
+
text, count = string.gsub(s, pattern, replace [, n])
 
text, count = gsub(s, pattern, replace [, n])
  +
text, count = (""):gsub(pattern, replace [, n])
   
  +
== Arguments ==
This is a very powerful function and can be used in multiple ways. Used simply it can replace all instances of the pattern provided with the replacement. A pair of values is returned, the modified string and the number of substitutions made. The optional fourth argument n can be used to limit the number of substitutions made:
 
  +
; s : {{api|t=t|string}} - String to search.
  +
; pattern : {{api|t=t|string}} - Pattern matching expression, covered in [[HOWTO: Use Pattern Matching]] or the [http://lua-users.org/wiki/PatternsTutorial Patterns Tutorial on Lua-Users.org].
  +
; replace : {{api|t=t|string}}|{{api|t=t|function}}|{{api|t=t|table}} - Replacement text, or a function which may return replacement text, or a lookup table which may contain replacements (see details).
  +
; n : {{api|t=t?|number}} - The maximum number of substitutions (unlimited if omitted).
   
  +
== Returns ==
  +
; text : {{api|t=t|string}} - Resulting string after any substitutions.
  +
; count : {{api|t=t|number}} - Number of times a substitution was performed.
  +
  +
== Details ==
  +
* For each occurrence of <code>pattern</code> found within <code>s</code> (limited to <code>n</code> occurrences), gsub looks for a potential replacement based on the type of <code>pattern</code>:
  +
** {{api|t=t|string}} - A simple substitution, including captures as $1, $2, and so on.
  +
** {{api|t=t|function}} - The function receives any captures as arguments and may return a replacement (a string). No change happens when the function returns nil; however, this counts toward <code>n</code>.
  +
** {{api|t=t|table}} - If the matched text is a table key, then it is replaced by the table value (a string). No change happens when the key is absent (value is nil); however, this counts toward <code>n</code>.
  +
* When different substitutions are needed on a single string, the function and lookup table alternatives may be more efficient than calling gsub multiple times. (Particularly if the lookup table already exists.)
  +
  +
== Examples ==
  +
Simple substitutions:
 
> = string.gsub("Hello banana", "banana", "Lua user")
 
> = string.gsub("Hello banana", "banana", "Lua user")
 
Hello Lua user 1
 
Hello Lua user 1
Line 10: Line 29:
 
bAnAna 2
 
bAnAna 2
   
  +
Simple substitutions with captures:
If a capture is used this can be referenced in the replacement string using the notation %capture_index, e.g.,
 
 
 
> = string.gsub("banana", "(an)", "%1-") -- capture any occurrences of "an" and replace with inserted trailing dashes
 
> = string.gsub("banana", "(an)", "%1-") -- capture any occurrences of "an" and replace with inserted trailing dashes
 
ban-an-a 2
 
ban-an-a 2
Line 19: Line 37:
 
bnanaa 2
 
bnanaa 2
   
  +
Using a function with captures:
If the replacement is a function, not a string, the arguments passed to the function are any captures that are made. If the function returns a string, the value returned is substituted back into the string. Just like string.find() we can use regular expressions to search in strings. Patterns are covered in the [http://lua-users.org/wiki/PatternsTutorial Patterns Tutorial on Lua-Users.org], and [[HOWTO: Use Pattern Matching]].
 
 
 
> = string.gsub("Hello Lua user", "(%w+)", print) -- print any words found
 
> = string.gsub("Hello Lua user", "(%w+)", print) -- print any words found
 
Hello
 
Hello
Line 32: Line 49:
 
> = string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any occurrences of "an"
 
> = string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any occurrences of "an"
 
bnanaa 2
 
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

Revision as of 21:10, 14 June 2021

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 - 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?Optional. Could be nil. - The maximum number of substitutions (unlimited if omitted).

Returns

text
string - Resulting string after any substitutions.
count
number - Number of times a substitution was performed.

Details

  • For each occurrence of pattern found within s (limited to n occurrences), gsub looks for a potential replacement based on the type of pattern:
    • string - A simple substitution, including captures as $1, $2, and so on.
    • function - The function receives any captures as arguments and may return a replacement (a string). No change happens when the function returns nil; however, this counts toward n.
    • table - If the matched text is a table key, then it is replaced by the table value (a string). No change happens when the key is absent (value is nil); however, this counts toward n.
  • When different substitutions are needed on a single string, the function and lookup table alternatives may be more efficient than calling gsub multiple times. (Particularly if the lookup table already exists.)

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