Lua:gmatch多线串?

时间:2017-07-17 11:32:56

标签: 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 string.find( line, term, 1, true ) then
      table.insert( matches, { line = i, code = line } )
    end
  end
  return matches
end

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

你的解决方案对我来说似乎很好。使用单个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")