我有一个像“function *()”这样的搜索字符串。 *是通配符。我想要一个包含所有匹配字符串列表的表。
e.g。 如果我用searchstring“function *()”
搜索这个字符串function one()
print("Hello")
end
local function two()
print("World")
end
它应该返回表{“function one()”,“function two()”}。我怎么能在LUA中做到这一点?
答案 0 :(得分:2)
local function search(text, searchstring)
local result = {}
local pattern = searchstring:gsub("*", "\0"):gsub("%p", "%%%0"):gsub("%z", ".-")
for w in text:gmatch(pattern) do
table.insert(result, w)
end
return result
end
用法:
local text = [[
function one()
print("Hello")
end
local function two()
print("World")
end
]]
local searchstring = "function *()"
local result = search(text, searchstring) --> {"function one()", "function two()"}