6

我有一个用于替换字符串的搜索替换脚本。它已经具有执行不区分大小写搜索和“转义”匹配的选项(例如,允许在搜索中搜索 % (等)。

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

2 回答 2

6

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

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-19T16:12:58.930 回答
1

你的意思是如果你通过 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-19T15:16:42.703 回答