如何在LUA中替换整个字符串,忽略像冒号这样的特殊字符

我正在尝试仅替换整个句子中的整个单词,但我尝试了几种方法,但它仅仅不能正常工作。我希望我可以在这里得到些帮助。

所以我使用了以下文章中的代码: 使用string.gsub来替换字符串,但仅限整个单词

function replacetext(source, find, replace, wholeword)
  if wholeword then
    find = '%f[%a]'..find..'%f[%A]'
  end
  return (source:gsub(find,replace))
end

这是我用来测试的演示代码。

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

我得到的输出是以下内容:

|Hplayer:NOODLE-SomeServer:374:WHISPER:YARNBARN-SOMESERVER[113:|cFF342345NOODLE|r]|h whispers: this is a test NOODLE YarnBarnME testing for % NOODLE finally :NOODLE# NOODLE

然而,上面的内容是不正确的,因为它匹配了前面带有冒号的单词,并且显然考虑了特殊或魔法字符。

正确的返回应该像这样:

|Hplayer:YarnBarn-SomeServer:374:WHISPER:YARNBARN-SOMESERVER[113:|cFF342345YarnBarn|r]|h whispers: this is a test NOODLE YarnBarnME testing for % NOODLE finally :YarnBarn# NOODLE

我正在尝试使其用仅限整个单词的方式替换前后没有字符,包括特殊字符或冒号。这就是为什么在应该是正确输出的内容中,您会注意到只有独立单词_YarnBarn_被转换为_NOODLE_。

我不想将句子分割或仅扫描其中的一部分。我确实需要它解析整个句子并仅替换整个单词。我尝试了几个变体,但似乎无法正常工作。任何帮助都将不胜感激!

点赞
用户12967614
用户12967614

@EgorSkriptunoff 发布了这个解决方案。

function replacetext(source, find, replace, wholeword)
  if wholeword then
    find = "%f[^%z%s]"..find.."%f[%z%s]"
  end
  return (source:gsub(find,replace))
end
2020-02-29 14:52:41