String:gsub()

The gsub method on a string uses Lua Pattern Matching to perform a find and replace operation.

It takes three arguments:

  1. The pattern to be matched

  2. Replacement string or function or table (ie. the pattern key)

  3. Optional: The maximum number of matches to replace

gsub returns a copy of all occurrences of the pattern that have been replaced and the total number of matches that occurred.

Here are few examples for the different types of replacements:

The string value is used as the key for the replacement.

Additionally, the % can be used here as an escape character:

  • any sequence using %n (with n between 1 and 9), stands for the value of the Nth captured substring.

  • The sequence %0 stands for the whole match.

  • The sequence %% stands for a single %.

local Count local S = "hello world" S, Count = S:gsub("(%w+)", "%1 %1") trace(S) -- "hello hello world world" trace(Count) -- 1

Here we have captured the string and used the capture to duplicate it.

The table is queried for every match using the first capture as the key. If the pattern specifies no captures, then the whole match is used as the key.

The function is called every time a match occurs, with all captured substrings passed as arguments. If the pattern specifies no captures, then the whole match is passed as a sole argument.

If the returned function value is false or nil, then there is no replacement.

Notice hello and world are captured by “(%w+)” and passed in order for the function to replace.

 

Related pages