使用string.gsub替换字符串,但只替换完整的单词。

我有一个搜索替换脚本,可以用来替换字符串。它已经有了可以大小写不敏感搜索和“转义”匹配(例如允许在搜索中使用%(等符号)的选项。

然而,现在我被要求仅匹配整个单词,我尝试在每个端点添加%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

我现在有一种做我想做的事情的方法,但它不太优雅。有没有更好的方法?

   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

原文链接 https://stackoverflow.com/questions/10226150

点赞
stackoverflow用户1208078
stackoverflow用户1208078

你的意思是如果你传递nocase() foo,你想要[fooFOO]而不是[fF][oO][oO]吗?如果是这样,你可以尝试这个?

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 split(strText)
    local words = {}
    string.gsub(strText, "(%a+)", function(w)
                                    table.insert(words, w)
                                  end)
    return words
end

一旦你把单词分开,就很容易在表中遍历单词并对每个单词进行全面比较。

2012-04-19 15:16:42
stackoverflow用户501459
stackoverflow用户501459

现在有一种方法可以做我想要做的事情,但它不够优雅。有更好的方法吗?

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
2012-04-19 16:12:58