Lua脚本模式匹配问题

首先,我在整个脚本编写过程中一直将此网站作为参考,并且它非常出色。我非常感激这里的每个人都是如此有用和知识渊博。考虑到这一点,我有一个关于 Lua 中匹配(模式匹配)的问题。我正在编写一个脚本,该脚本基本上从文件中获取输入并将其导入表中。我正在检查文件中作为我查询的主机的特定 MAC 地址。

  if macFile then
     local file = io.open(macFile)

     if file then
    for line in file:lines() do
      local f = line
      i, j = string.find ( f, "%x+" )
      m = string.sub(f, i, j)
      table.insert( macTable, m )
    end
    file:close()
     end

这将文件解析为我稍后将使用的格式。一旦构建了表,我运行模式匹配序列,尝试通过迭代表并根据当前迭代与模式匹配来匹配来自表中的 MAC:

local output = {}
t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")
for key,value in next,macTable,nil do
        a, p = string.find ( s, value )
        matchFound = string.sub(s, a, p)
        table.insert( output, matchFound )
end

这不返回任何输出,尽管当我在 Lua 提示符中逐行输入时,它似乎有效。我相信变量被正确传递。有什么建议吗?

原文链接 https://stackoverflow.com/questions/3459215

点赞
stackoverflow用户206020
stackoverflow用户206020

我现在正要下班,无法深入查看您的问题,但下面的两行似乎非常奇怪。

t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")

基本上您正在删除字符串t中的所有':'字符。之后,您最终得到的s"000000000000"。这可能不是您想要的答案?

2010-08-11 15:27:21
stackoverflow用户415823
stackoverflow用户415823

如果您的 macFile 使用如下的结构:

012345678900
008967452301
000000000000
ffffffffffff

以下脚本应该可以工作:

macFile = "./macFile.txt"
macTable = {}

if macFile then
    local hFile = io.open(macFile, "r")
    if hFile then
        for line in hFile:lines() do
            local _,_, sMac = line:find("^(%x+)")
            if sMac then
                print("Mac address matched: "..sMac)
                table.insert(macTable, sMac)
            end
        end
        hFile:close()
    end
end

local output = {}
t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")

for k,v in ipairs(macTable) do
    if s == v then
        print("Matched macTable address: "..v)
        table.insert(output, v)
    end
end
2010-08-12 19:05:24