Lets say I have a string, local str = "Hello, I like scripting!"
, and lets say I wanted to remove a certain part of it, so that way it says this: local str = "I like scripting!
, but how would I do this within a script? I already know how to use someString:sub(a, b) -- " a ", " b " are numbers. With " a " being the min, and " b " being the max
But :sub(a, b)
does not remove a part of a string. Can someone show me how to remove a certain piece of a string using a script?
All built in string library functions can be seen here.
The one you’re looking for is string.gsub(string s, string pattern, Variant repl)
. The description reads: Returns a copy of s in which all (or the first n, if given) occurrences of the pattern have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.
So, in your example to get from “Hello, I like scripting!”, to “I like scripting!” you would do:
local str = "Hello, I like scripting!"
local newStr, replaced = string.gsub(str, "Hello, ", "")
print("Replaced "..replaced.." occurrences:")
print(newStr)
--> Replaced 1 occurrences:
--> I like scripting!
But, be warned: this using string patterns so if you end up wanting to replace a string that contains a “magic character” then you will have to escape that character with a percentage sign (%) before it.
For example, if you want to replace a .
you would put %.
in your pattern to escape it.
Is there a reason that string patterns exist? It seems / sounds strange that you would have to put a percentage symbol in front of a dot.
As above: If it’s easy to define what you want to replace, then you can use gsub.
If you have a more complicated scenario, the pattern you want is to break out the pieces that you do want using string.sub and concatenate them back together into one piece: local newString = str:sub(1, A) .. str:sub(B, -1)
. If you have a variable number of pieces you can put them in a table and concatenate them all at once using table.concat
.
Dot normally means “any character”. If you want an actual dot character you write the % in front to specify “No, I literally want a dot character”. In general % in front of something means something special / different than the normal meaning for that thing in Lua’s string patterns.