使用string.gsub替换字符串,但只能替换整个单词

Jan*_*e T 6 lua

我有一个搜索替换脚本,可以替换字符串.它已经可以选择进行不区分大小写的搜索和"转义"匹配(例如,允许在搜索中搜索%(等).

我怎么现在只被要求匹配整个单词,我已经尝试将%s添加到每一端,但是这与字符串末尾的单词不匹配,我无法找出如何陷入白色 - 在更换过程中发现的空间物品完好无损.

我是否需要使用string.find重做脚本并为单词检查添加逻辑,或者使用模式添加逻辑.

我用于不区分大小写和转义的项目的两个函数如下所示都返回要搜索的模式.

    --   Build Pattern from String for case insensitive search
function nocase (s)
      s = string.gsub(s, "%a", function (c)
            return string.format("[%s%s]", string.lower(c),
                                           string.upper(c))
          end)
      return s
    end
function strPlainText(strText)
    -- Prefix every non-alphanumeric character (%W) with a % escape character, where %% is the % escape, and %1 is original character
    return strText:gsub("(%W)","%%%1")
end 
Run Code Online (Sandbox Code Playgroud)

我有办法做我现在想做的事,但它不够优雅.有没有更好的办法?

   local strToString = ''
     local strSearchFor = strSearchi
    local strReplaceWith = strReplace
    bSkip = false
    if fhGetDataClass(ptr) == 'longtext' then
        strBoxType = 'm'
    end
   if pWhole == 1 then
    strSearchFor = '(%s+)('..strSearchi..')(%s+)'
    strReplaceWith = '%1'..strReplace..'%3'
    end
    local strToString = string.gsub(strFromString,strSearchFor,strReplaceWith)
    if pWhole == 1 then
    -- Special Case search for last word and first word
        local strSearchFor3 = '(%s+)('..strSearchi..')$'
        local strReplaceWith3 = '%1'..strReplace
        strToString = string.gsub(strToString,strSearchFor3,strReplaceWith3)
        local strSearchFor3 = '^('..strSearchi..')(%s+)'
        local strReplaceWith3 = strReplace..'%2'
        strToString = string.gsub(strToString,strSearchFor3,strReplaceWith3)
    end
Run Code Online (Sandbox Code Playgroud)

Mud*_*Mud 5

有一种方法可以做我现在想要的,但这很不雅致。有没有更好的办法?

Lua的模式匹配库有一个未记录的功能,称为Frontier Pattern,它将使您可以编写以下内容:

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

local source  = 'test testing this test of testicular footest testimation test'
local find    = 'test'
local replace = 'XXX'
print(replacetext(source, find, replace, false))  --> XXX XXXing this XXX of XXXicular fooXXX XXXimation XXX    
print(replacetext(source, find, replace, true ))   --> XXX testing this XXX of testicular footest testimation XXX
Run Code Online (Sandbox Code Playgroud)