I'm having an issue trying to replace just whole words in a sentence. I've tried several methods but it just doesn't work properly. I'm hoping I can get some help here.
So I used the code from the following article: Use string.gsub to replace strings, but only whole words
function replacetext(source, find, replace, wholeword)
if wholeword then
find = '%f[%a]'..find..'%f[%A]'
end
return (source:gsub(find,replace))
end
Here is the demo code I use to test this.
local source = '|Hplayer:YarnBarn-SomeServer:374:WHISPER:YARNBARN-SOMESERVER[113:|cFF342345YarnBarn|r]|h whispers: this is a test YarnBarn YarnBarnME testing for % YarnBarn finally :YarnBarn# YarnBarn'
local find = 'YarnBarn'
local replace = 'NOODLE'
print(replacetext(source, find, replace, true ))
The output I get is the following:
|Hplayer:NOODLE-SomeServer:374:WHISPER:YARNBARN-SOMESERVER[113:|cFF342345NOODLE|r]|h whispers: this is a test NOODLE YarnBarnME testing for % NOODLE finally :NOODLE# NOODLE
However, the above is incorrect as it's matching words with the colon in the front and it's obviously taking special or magic characters into account.
The correct return should be like this:
|Hplayer:YarnBarn-SomeServer:374:WHISPER:YARNBARN-SOMESERVER[113:|cFF342345YarnBarn|r]|h whispers: this is a test NOODLE YarnBarnME testing for % NOODLE finally :YarnBarn# NOODLE
I'm trying to get it to replace whole words exactly with nothing in the front or back of the word. This includes special characters or colon. That is why on the what should be the correct output, you will notice only the independent words of YarnBarn were converted to NOODLE.
I don't want to chop up the sentence or just scan a portion of it. I really need it to parse the entire sentence and replace just the whole words. I've tried several variations and I just can't seem to get it to work right. Any help would be greatly appreciated!!!