WoW:API gsub: Difference between revisions

34 bytes added ,  15 August 2023
m
Move page script moved page API gsub to WoW:API gsub without leaving a redirect
(Added link)
m (Move page script moved page API gsub to WoW:API gsub without leaving a redirect)
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{:Lua/Libshortcut|gsub|string.gsub}}
{{luaapi}}
  string.gsub(s, pattern, replace [, n])
  string.gsub(s, pattern, replace [, n])
gsub(s, pattern, replace [, n])
strreplace(s, pattern, replace [, n])


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:
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:
Line 18: Line 20:
  bnanaa  2
  bnanaa  2


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]].
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 the [[pattern matching]] HOWTO.


  > = string.gsub("Hello Lua user", "(%w+)", print)  -- print any words found
  > = string.gsub("Hello Lua user", "(%w+)", print)  -- print any words found
Line 31: Line 33:
  > = string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any "an"s
  > = string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any "an"s
  bnanaa  2
  bnanaa  2
{{LUA}}
Anonymous user