Lua中使用string.gsub进行简单搜索?

4
使用Lua的string.find函数时,可以传递第四个可选参数以启用普通搜索。来自Lua维基的说明:

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函数实现相同的简单搜索。


如果您不介意我问一下,为什么您要尝试使用gsub来做一些它本来不应该做的事情呢? - itdoesntwork
我正在尝试用另一个字符串替换一个字符串的大块内容。 - David
哦,我做出了那个评论,假设字符串库中已经存在一个明文搜索替换函数,但是阅读文档后,我不确定它是否存在。 - itdoesntwork
我非常确定没有 :( - David
1
在搜索字符串中转义每个非字母数字字符。 - Etan Reisner
3个回答

2
这里有一个简单的库函数用于文本替换:
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


2
由于 OP 想要在纯文本中使用 gsub,因此应该使用 return text:sub(1,b-1) .. new .. text:sub(e+1):replace(old, new) - hjpotter92

2
使用此函数来转义搜索字符串中的所有魔法字符(仅限这些字符)。
function escape_magic(s)
  return (s:gsub('[%^%$%(%)%%%.%[%]%*%+%-%?]','%%%1'))
end

2
我原以为标准库中有相关功能,但事实上并没有。因此,解决方案是转义匹配模式中的特殊字符,使其不再执行默认的功能。
以下是一般步骤:
1.获取匹配模式字符串
2.将任何特殊字符替换为%加特殊字符(例如,%变成%%[变成%[
3.将其作为搜索模式来替换文本

最简单的实现方式是:pattern:gsub('%W', function(x) return '%'..x end) - hjpotter92
2
@hjpotter92,或者pattern:gsub('%W','%%%1'),尽管%p可能比%W更合适。 - lhf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接