Lua 用 string.gsub 简单搜索?

Lua plain searching with string.gsub?

使用 Lua 的 string.find 函数,您可以传递一个可选的第四个参数以启用简单搜索。来自 Lua wiki:

The pattern argument also allows more complex searches. See the PatternsTutorial for more information. We can turn off the pattern matching feature by using the optional fourth argument plain. plain takes a boolean value and must be preceeded by index. E.g.,

= string.find("Hello Lua user", "%su")         -- find a space character followed by "u"

10      11

= string.find("Hello Lua user", "%su", 1, true) -- turn on plain searches, now not found

nil

基本上,我想知道如何使用 Lua 的 string.gsub 函数完成相同的简单搜索。

我希望标准库中有这方面的东西,但没有。那么,解决方案就是对模式中的特殊字符进行转义,这样它们就不会执行它们通常的功能。

总体思路如下:

  1. 获取模式字符串
  2. % 替换任何特殊字符(例如,% 变为 %%[ 变为 %[
  3. 将其用作替换文本的搜索模式

这是一个简单的文本替换库函数:

function string.replace(text, old, new)
  local b,e = text:find(old,1,true)
  if b==nil then
     return text
  else
     return text:sub(1,b-1) .. new .. text:sub(e+1)
  end
end

此函数可以调用为newtext = text:replace(old,new)

请注意,这只会替换 text 第一次 出现的 old

使用此函数转义搜索字符串中的所有魔法字符(并且仅转义那些魔法字符)。

function escape_magic(s)
  return (s:gsub('[%^%$%(%)%%%.%[%]%*%+%-%?]','%%%1'))
end