string.gsub()

Type Function
Library string.*
Return value String
Revision Current Public Release (2014.2393)
Keywords string, gsub, sub, search
See also string.find()
string.gmatch()
string.match()

Overview

Replace all occurrences of a pattern in a string.

Syntax

string.gsub( s, pattern, repl [, n] )

s:gsub( pattern, replace [,n] )
s (required)

String. The string to be searched.

pattern (required)

String. A string specifying the pattern to match. See Lua String Manipulation.

repl (required)

String. If repl is a string, its value is used for the replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the nth captured substring. The sequence %0 stands for the whole match and the sequence %% stands for a single %.

If repl is a table, the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, the whole match is used as the key.

If repl is a function, this function is called every time a match occurs, with all captured substrings passed as arguments in order; if the pattern specifies no captures, the whole match is passed as a sole argument.

If the value returned by the table query or by the function call is a string or a number, it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (the original match is kept in the string).

n (optional)

Number. Number of occurrences of pattern to replace.

Example

print( string.gsub( "Hello banana", "banana", "Corona user" ) ) 
print( string.gsub( "banana", "a", "A", 2 ) )             -- limit substitutions made to 2
print( string.gsub( "banana", "(an)", "%1-" ) )           -- capture any occurances of "an" and replace
print( string.gsub( "banana", "a(n)", "a(%1)" ) )         -- brackets around n's which follow a's
print( string.gsub( "banana", "(a)(n)", "%2%1" ) )        --reverse any "an"s
print( string.gsub( "Hello Lua user", "(%w+)", print ) )  --print any words found
print( string.gsub( "Hello Lua user", "(%w+)", function(w) return string.len(w) end ) )  --replace with lengths
print( string.gsub( "banana", "(a)", string.upper ) )                                    --make all 'a's found uppercase
print( string.gsub( "banana", "(a)(n)", function(a,b) return b..a end ) )                --reverse any "an"s
print( string.gsub( "The big {brown} fox jumped {over} the lazy {dog}.", "{(.-)}", function(a) print(a) end ) )
print( string.gsub( "The big {brown} fox jumped {over} the lazy {dog}.", "{(.*)}", function(a) print(a) end ) )