I want to use gsub in a text to change a exact string.
local Text = "Here is an apple and there is a pineapple." local NewText = Text:gsub("apple","grape") print(NewText)
--Output --Here is an grape and there is a pinegrape.
It change pineapple to pinegrape and I do not want that to happen.
how to use gsub with an exact string? It change pineapple to pinegrape and I do not want that to happen.
If you do not want it to change anything prefixing the word "apple" such as "pineapple" then only replace the word "apple" with whitespace in front of it. %s
is the white space pattern, so we would use "%apple"
local text = "I love apples but pineapples are bad!" local finalText = text:gsub("%sapple", " grape") --// notice there is a space infront of the `g` in grape because it will replace the space and there will be no separator between `grape` and the word previously before. print(finalText)
Output:
I love grapes but pineapples are bad!