首先,我已使用该网站作为完成整个脚本处理的基准,它一直美妙。我很欣赏多么有用,知识渊博的每个人都在这里。考虑到这一点,我有一个关于在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提示符下输入它一行行,它似乎工作返回任何输出。这些变量传递正确的,我相信。任何建议?

有帮助吗?

解决方案

如果您的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

其他提示

我刚刚下班离开,不能有你的问题更深入地了解现在,但接下来的两行似乎很奇怪。

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

基本上要删除所有':'在串t字符。然后你最终s存在"000000000000"。这可能不是你想要的?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top