在Lua中进行字符串模式匹配

4

我有以下字符串需要使用 Lua 分割成一个表格:

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

结果应该放入一个类似于这样的表中:

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

我尝试过以下代码:

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

那是我最好的尝试。

3个回答

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+)")

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并添加)以进行捕获

1

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

  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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接