模式匹配Lua中的字符串

时间:2010-08-13 17:19:40

标签: lua lua-patterns

我使用Lua将以下字符串拆分为表格: (数据彼此对齐。我没有找到如何在此网站上编写格式的文件)

  

IP:192.168.128.12
  MAC:AF:3G:9F:c9:32:2E
  到期日:2010年8月13日星期五20:04:53
  剩余时间:11040秒

结果应该放在这样的表格中:

  

t = {“IP”:“192.168.128.12”,“MAC”:“AF:3G:9F:c9:32:2E”,“Expires”:“Fri Aug 13 20:04:53 2010”, “剩下的时间”:“11040秒”}

我尝试过:

for k,v in string.gmatch(data, "([%w]+):([%w%p%s]+\n") do
  t[k] = v
end

这是我最好的尝试。

3 个答案:

答案 0 :(得分:3)

如果我理解了您的用例,则应遵循以下规则。可能需要稍微调整一下。

local s = "IP: 192.168.128.12 MAC: AF:3G:9F:c9:32:2E Expires: Fri Aug 13 20:04:53 2010 Time Left: 11040 seconds"
local result = {}
result["IP"] = s:match("IP: (%d+.%d+.%d+.%d+)")
result["MAC"] = s:match("MAC: (%w+:%w+:%w+:%w+:%w+:%w+)")
result["Expires"] = s:match("Expires: (%w+ %w+ %d+ %d+:%d+:%d+ %d+)")
result["Time Left"] = s:match("Time Left: (%d+ %w+)")

答案 1 :(得分:2)

假设“数据彼此对齐”意味着类似以下内容:

IP:          192.168.128.12
MAC:         AF:3G:9F:c9:32:2E
Expires:     Fri Aug 13 20:04:53 2010
Time Left:   11040 seconds

<pre>标记可用于保持对齐。

尽量减少对现有代码的更改:

for k,v in string.gmatch(data, "(%w[%w ]*):%s*([%w%p ]+)\n") do t[k] = v end
  • 将第一次捕获更改为(%w[%w ]*),以避免前导空格并在Time Left中获取空间
  • %s*之后添加了:,以避免在捕获的值中引出空格
  • 在第二次捕获中将%s更改为空格,以避免捕获\n
  • 将拼写错误gmath修改为gmatch并添加)以进行捕获

答案 2 :(得分:1)

以下模式适用于您,前提是:

  1. IP地址是带小数点的表示法。
  2. MAC地址是以冒号分隔的十六进制。
  3. 注意:问题中提供的MAC地址为“G”,不是十六进制数字。

    编辑:在详细考虑了您的问题之后,我扩展了我的答案,以展示如何将多个实例捕获到表格中。

    sString = [[
    IP: 192.168.128.16
    MAC: AF:3F:9F:c9:32:2E
    Expires: Fri Aug 1 20:04:53 2010
    Time Left: 11040 seconds
    
    IP: 192.168.128.124
    MAC: 1F:3F:9F:c9:32:2E
    Expires: Fri Aug 3 02:04:53 2010
    Time Left: 1140 seconds
    
    IP: 192.168.128.12
    MAC: 6F:3F:9F:c9:32:2E
    Expires: Fri Aug 15 18:04:53 2010
    Time Left: 110 seconds
    ]]
    
    local tMatches = {}
    
    for sIP, sMac, sDate, sSec in sString:gmatch("IP:%s([%d+\.]+)%sMAC:%s([%x+:]+)%sExpires:%s(.-)%sTime%sLeft:%s(%d+)%s%w+") do
        if sIP and sMac and sDate and sSec then
            print("Matched!\n"
                    .."IP: "..sIP.."\n"
                    .."MAC: "..sMac.."\n"
                    .."Date: "..sDate.."\n"
                    .."Time: "..sSec.."\n")
    
            table.insert(tMatches, { ["IP"]=sIP, ["MAC"]=sMac, ["Date"]=sDate, ["Expires"]=sSec })
        end
    end
    
    print("Total Matches: "..table.maxn(tMatches))
    
    for k,v in ipairs(tMatches) do
        print("IP Address: "..v["IP"])
    end
    
相关问题