Lua:gmatch多行字符串?
我试图创建一个函数,通过一些代码来搜索搜索词所在的行,以及该行的索引。代码是一个包含新行字符的多行字符串。我想用gmatch来做这个,但是我不知道怎么做 这是我目前的代码。这很糟糕,但我想不出更好的办法:Lua:gmatch多行字符串?,lua,string-matching,Lua,String Matching,我试图创建一个函数,通过一些代码来搜索搜索词所在的行,以及该行的索引。代码是一个包含新行字符的多行字符串。我想用gmatch来做这个,但是我不知道怎么做 这是我目前的代码。这很糟糕,但我想不出更好的办法: local function search( code, term ) local matches = {} local i = 0 for line in string.gmatch( code, "[^\r\n]+" ) do i = i + 1 if stri
local function search( code, term )
local matches = {}
local i = 0
for line in string.gmatch( code, "[^\r\n]+" ) do
i = i + 1
if string.find( line, term, 1, true ) then
table.insert( matches, { line = i, code = line } )
end
end
return matches
end
任何帮助都将不胜感激 我觉得你的解决方案不错。使用单个
gmactch
循环的问题在于您需要报告行号。下面的代码通过在代码中嵌入行号来避免这种情况。我用@
标记行号。您可以使用源代码中未出现的任何字符,甚至是\0
之类的字符
function search(code,term)
for a,b in code:gmatch("@(%d+):([^\n]-"..term.."[^\n]-)\n") do
print(a)
print(b)
end
end
local n=0
code="\n"..code
code=code:gsub("\n", function () n=n+1 return "\n@"..n..":" end)
search(code,"matc")
要正确计算空行数:
对于string.gmatch(code,“([^\r\n]*)\r?\n?”)是否执行
为什么您觉得这段代码很糟糕?@lhf它一行一行地检查每一行,只是为了看看其中一行是否有正确的字符串,而不是将行作为一个整体进行查看,因为它是一个字符串。另外,我加1的那部分我觉得不对。循环时我习惯于k和v。