1

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

Xruptor
  • 31
  • 2
  • `find = "%f[^%z%s]"..find.."%f[%z%s]"` – Egor Skriptunoff Feb 26 '20 at 16:32
  • @EgorSkriptunoff That worked! Can you explain why it works though? I'm trying to learn and apparently %z matches a byte 0. So I'm assuming you are checking for a byte 0 before and after the word? Not sure how that would even work properly. – Xruptor Feb 26 '20 at 16:54
  • Lua patterns work as if any string was prepended and appended by byte 0. – Egor Skriptunoff Feb 26 '20 at 18:10
  • @EgorSkriptunoff AH! That totally makes sense now as to why you are doing checks for %z. This is good to know for the future thanks! – Xruptor Feb 27 '20 at 12:33
  • @EgorSkriptunoff If possible can you post your submission as an Answer below? That way I can mark it as the accepted answer. Thanks! – Xruptor Feb 27 '20 at 12:36

1 Answers1

0

@EgorSkriptunoff posted this solution.

function replacetext(source, find, replace, wholeword)
  if wholeword then
    find = "%f[^%z%s]"..find.."%f[%z%s]"
  end
  return (source:gsub(find,replace))
end
Xruptor
  • 31
  • 2