String
string.gsub
Shared
Replaces occurrences of a pattern with a replacement
Syntax
local result, count = string.gsub(input, pattern, replacement, max_replacements = nil)Parameters
| Type | Name | Description |
|---|---|---|
string | input | String to be converted |
string | pattern | Lua pattern to find |
string, table or function | replacement | Replacement string, table, or function |
int | max_replacements | Maximum number of replacements to make |
Returns
| Type | Name | Description |
|---|---|---|
string | result | Altered string with replacements |
int | count | Number of substitutions that occurred |
Examples
local result, count = string.gsub("hello world", "world", "Lua")
engine.print("info", result) --'hello Lua'
engine.print("info", count) --1local result = string.gsub("aaa", "a", "b")
engine.print("info", result) --'bbb'local result, count = string.gsub("aaa", "a", "b", 2)
engine.print("info", result) --'bba'
engine.print("info", count) --2local result = string.gsub("hello world", "%a+", "word")
engine.print("info", result) --'word word'local result = string.gsub("h e l l o", " ", "")
engine.print("info", result) --'hello'local result = string.gsub("call 555-1234", "%d", "X")
engine.print("info", result) --'call XXX-XXXX'local result = string.gsub("hello world", "(%a+)", "<%1>")
engine.print("info", result) --'<hello> <world>'local result = string.gsub("first second", "(%a+) (%a+)", "%2 %1")
engine.print("info", result) --'second first'local result = string.gsub("I have 2 apples and 3 oranges", "%d+", function(n)
return tonumber(n)*2
end)
engine.print("info", result) --'I have 4 apples and 6 oranges'local replacements = {
hello = "goodbye",
world = "moon"
}
local result = string.gsub("hello world", "%a+", replacements)
engine.print("info", result) --'goodbye moon'local result = string.gsub("hello world from lua", "%a+", function(word)
return string.upper(string.sub(word, 1, 1))..string.sub(word, 2)
end)
engine.print("info", result) --'Hello World From Lua'local html = "<p>Hello <b>world</b></p>"
local result = string.gsub(html, "<[^>]+>", "")
engine.print("info", result) --'Hello world'local result = string.gsub("cost: $5.00", "%$", "USD ")
engine.print("info", result) --'cost: USD 5.00'local result = string.gsub("my_variable_name", "_(%a)", function(letter)
return string.upper(letter)
end)
engine.print("info", result) --'myVariableName'local result, count = string.gsub("hello", "xyz", "abc")
engine.print("info", result) --'hello'
engine.print("info", count) --0