Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

how to use gsub with an exact string?

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.

2 comments

0

WHat do you exactly want to happen XD?

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.

1 answer

#####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!

This discussion is preserved as it was. New answers, comments, and votes are closed.