string.gsub() function in Lua programming


There are scenarios when we want to change a pattern that we found in a string with our pattern, and in Lua for that we have a famous library function, named the string.gsub() function.

The string.gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern.

Syntax

string.gsub(x,a,b)

In the above syntax, the x identifier is used to denote the string in which we are trying to replace a pattern, the a identifier is the pattern that we want to replace, and the b identifier is the pattern with which we want to replace the substring that we found.

Example

Now, let’s consider a basic example of the string.gsub() in Lua.

Consider the example shown below −

 Live Demo

s = string.gsub("Lua is good", "good", "great")
print(s)--> Lua is great

Output

Lua is great

Example

Let’s consider one more simple example, so that you understand it completely.

Consider the example shown below −

 Live Demo

s = string.gsub("hello lii", "l", "x")
print(s)

Output

hexxo xii

It should be noted that if we provide a pattern that is not present in the string, then nothing will change, the string will remain the same.

Example

Consider the example shown below −

 Live Demo

s = string.gsub("Lua is good", "ok", "great")
print(s)

Output

Lua is good

There’s also a fourth argument that we can pass in the string.gsub() function and that fourth argument will be used to limit the number of substitutions to be made.

Example

Consider the example shown below −

 Live Demo

s = string.gsub("lua is lua and lua", "lua", "he",2)
print(s)

Output

he is he and lua

Updated on: 19-Jul-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements