Lua:gmatch 处理多行字符串?

我正在尝试创建一个函数来搜索一些代码,以找到搜索词所在的行以及该行的索引。代码是一个有换行符的多行字符串。我想使用 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

任何帮助将不胜感激!

点赞
用户107090
用户107090

你的解决方案对我来说很好。使用单个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")
2017-07-17 14:38:14