2010-08-11 81 views
0

首先,我一直在使用这个站点作为整个脚本编写过程的参考,它很棒。我很欣赏每个人都在这里的有用和知识。考虑到这一点,我有一个关于Lua中匹配(模式匹配)的问题。我正在编写一个脚本,它基本上从文件输入并将其导入到表中。我正在检查文件中的特定MAC地址,作为我正在查询的主机。Lua脚本模式匹配问题

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提示符中逐行输入它,它似乎工作。我相信变量正确传递。有什么建议么?

+0

什么'macFile'的内容是什么? – gwell 2010-08-11 15:58:26

回答

2

如果您macFile使用这样的结构:


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 
+0

非常感谢你们。亚当,那正是我所寻找的。它看起来不像简单的平等条件那么简单。我感谢你的时间。 – Timothy 2010-08-12 23:12:32

0

我刚刚离开工作,现在无法深入了解您的问题,但接下来的两行看起来很奇怪。

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

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

+0

那么,我输入的MAC文件基本上是一行一行,没有“:”的Mac。所以我的桌子上充满了许多不同的条目,全部格式化为“:”。所以,为了匹配表格格式,我需要格式化t。然而,在脚本中,变量t将被自动填充。但谢谢你的回信! – Timothy 2010-08-11 19:18:54

+0

您是否验证过能正确解析文件?您可以通过执行'for k,v(macTable)do print(k,v)end'来测试它。你能发布你想分析的文件的一部分吗? – ponzao 2010-08-12 07:02:12