Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

how to use gsub with an exact string?

Asked by 5 years ago

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.

0
WHat do you exactly want to happen XD? Igoralexeymarengobr 365 — 5y
0
This will change every word that reads as "apple" to grape. For a solution, you could use a gmatch to rule out non-singular worded versions instead to solve your issue. Ziffixture 6913 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago
Please accept this answer if it helped!

Question

how to use gsub with an exact string? It change pineapple to pinegrape and I do not want that to happen.

Answer

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"

Example

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!

Ad

Answer this question