Tom Bradely
Tom Bradely

Reputation: 81

How to parse a series of strings with spaces in between in Lua

I'm trying to parse a txt file which is in the format of host-name IP mac-address in Lua. All three separated with spaces, to try and then store it into a table using Lua.

I've tried doing this using :match function but can't see to get it to work.

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

It keeps on printing the location in memory of where each key/value is stored (I think).

I'm sure this is a relatively easy fix but I can't seem to see it.

Upvotes: 2

Views: 700

Answers (2)

Piglet
Piglet

Reputation: 28950

If hostname, ip and mac are separated by space your pattern may not use colons. I added a few changes to store the captures in the client table.

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

Alternatively:

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

then hostname is client[1] which is not very intuitive.

Upvotes: 2

brianolive
brianolive

Reputation: 1671

No colon in the regex:

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

Upvotes: 1

Related Questions