如何在Lua中解析一系列带有空格的字符串

我正在尝试解析一个以 host-name IP mac-address 格式的 txt 文件,并使用 Lua 将它们分离开,并尝试将其存储到表格中。

我已经尝试使用 :match 函数来实现,但无法使其正常工作。

function parse_input_from_file()
  array ={}
  file = io.open("test.txt","r")
  for line in file:lines() do
    local hostname, ip, mac = line:match("(%S+):(%S+):(%S+)")
    local client = {hostname, ip, mac}
  table.insert(array, client)
  print(array[1])
  end
end

它一直打印每个键/值存储的内存位置(我认为是这样)。

我相信这是一个相对容易的解决方案,但我无法看到它。

点赞
用户4403144
用户4403144

没有正则表达式中的冒号:

local sampleLine = "localhost 127.0.0.1 mac123"
local hostname, ip, mac = sampleLine:match("(%S+) (%S+) (%S+)")
print(hostname, ip, mac) -- localhost 127.0.0.1 mac123
2019-03-31 02:20:30
用户2858170
用户2858170

如果主机名、IP 和 MAC 地址之间用空格分隔,则您的模式可能不使用冒号。 我添加了一些更改,将捕获存储在客户端表中。

function parse_input_from_file()
  local clients ={}
  local file = io.open("test.txt","r")
  for line in file:lines() do
    local client = {}
    client.hostname, client.ip, client.mac = line:match("(%S+) (%S+) (%S+)")
    table.insert(clients, client)
  end
  return clients
end

for i,client in ipairs(parse_input_from_file()) do
   print(string.format("Client %d: %q %s %s", i, client.hostname, client.ip, client.mac))
end

或者:

local client = table.unpack(line:match("(%S+) (%S+) (%S+)"))

然后 hostnameclient [1],这不是很直观。

2019-03-31 16:41:04