我有一个用于替换字符串的搜索替换脚本。它已经具有执行不区分大小写搜索和“转义”匹配的选项(例如,允许在搜索中搜索 % (等)。
现在我被要求只匹配整个单词,我尝试在每一端添加 %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