在Lua中匹配字符串的模式。

我有以下字符串需要使用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", "Time Left": "11040秒"}

我尝试了:

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

`` `

这是我最好的尝试。

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

点赞
stackoverflow用户206020
stackoverflow用户206020

如果我理解你的用例,下面的代码应该可以解决问题。但可能需要一些微调。

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+)")
2010-08-13 18:02:42
stackoverflow用户415823
stackoverflow用户415823

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

  1. IP地址是十进制点分表示法。
  2. MAC地址是由冒号分隔的十六进制数。

注意:您问题中提供的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
2010-08-13 18:16:45
stackoverflow用户173806
stackoverflow用户173806

假设 "数据彼此对齐" 的意思是像下面这样:

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”的拼写错误,并添加了 ) 来捕获
2010-08-13 19:32:42