string.gsub

Substitute strings inside another string

Prototype

s, n = string.gsub (str, pattern, replacement, n)

Description

Returns a copy of str with matches to 'pattern' replaced by 'replacement', for a maximum of n times.
As a second result it returns the number of matches made.

'replacement' can be a string in which case it simply replaces the matching pattern. However %1 through to %9 in the replacement pattern can refer to captured strings in the source pattern. %% becomes %. Also, %0 in the replacement pattern refers to the entire matching string.

If 'replacement' is a function it is called for each match with the matching string as an argument. It should return a string which is the string to replace it with. If it returns nil the original string is retained.

If 'replacement' is a table then the matching string is looked up in the table for each match, and if found, the replacement is substituted.

See string.find for an explanation of regular expressions.

string.gsub ("nick eats fish", "fish", "chips") --> nick eats chips

-- example of using a function as the replacement

replacements = { 
   ["nice"] = "windy",
   ["walk"] = "stroll",
   }
   
s = "a nice long walk"

result = string.gsub (s, "%a+", 
  function (str)
  return replacements [str]
  end
  )

print (result) --> a windy long stroll

-- An alternative way of doing a table replacement using the above table:

result = string.gsub (s, "%a+", replacements)

print (result) --> a windy long stroll

-- You can call inbuilt functions too:

s = "a nice long walk"

result = string.gsub (s, "%f[%a]%a%a", string.upper)

print (result) --> a NIce LOng WAlk

If you need to search for something that is not a regular expression, you need to "fix up" the search string first. This should do it:

search = string.gsub (search, "[%%%]%^%-$().[*+?]", "%%%1")
The code above fixes all of the special characters recognized in a regular expression by preceding them with a percent symbol.

Lua functions

Topics