Replacing words in a string with another

Hello! I’m trying to replace a word within a string with another word. Whilst string.gsub() works for most cases, it may cause troubles for short words, like “me”. For example:

local str = "He is meeting me"
local result = string.gsub(str,"me","her")
print (result) -- "He is hereting her", obviously wrong

I’ve tried playing around string patterns, however, I encountered some problems. Whilst using "%Ame%A" works for most cases, it doesn’t work whenever the word in at the end or at the beginning of a sentence. For example:

local str = "me me me"
local result = string.gsub(str,"%Ame%A"," her ")
print (result) -- "me her me", also wrong

Is there a way to make it so it also matches the "me"s at the beginning and at the end?

Furthermore, is there a way to preserve the punctuation around the word? For example, using the code above, "me,me,me" would turn to "me her me".

Try this:

str:gsub("%sme%s", " her ")

It might not work for if it’s the last or first word of a sentence tho.

try this, might be some spelling mistake

function replaceWords(sentence: string, wordList: {})
local words = string.split(sentence," ")
local finalSentence = ""

for index, word in ipairs(words) do
local lowered = string.lower(word)
if wordList[lowered] ~= nil then
words[index] = wordList[lowered]
end
end

for  _,word in ipairs(words) do
finalSentence = finalSentence.." "..word
end

return finalSentence 
end
print(replaceWords("Oh no please help me",{["me"] = "her", ["help"] = "save"}))
2 Likes