我有一个搜索替换脚本,可以替换字符串.它已经可以选择进行不区分大小写的搜索和“转义”匹配(例如,允许在搜索中搜索%(等). 我怎么现在只被要求匹配整个单词,我已经尝试将%s添加
我怎么现在只被要求匹配整个单词,我已经尝试将%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
have a way of doing what I want now, but it’s inelegant. Is there a better way?
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