Parsing 如何在Lua中解析一系列中间有空格的字符串
我正在尝试解析一个txt文件,该文件的格式为Lua中的主机名IP mac地址。所有三个都用空格分隔,以尝试使用Lua将其存储到表中 我尝试过使用:match函数来实现这一点,但看不到如何让它工作Parsing 如何在Lua中解析一系列中间有空格的字符串,parsing,lua,Parsing,Lua,我正在尝试解析一个txt文件,该文件的格式为Lua中的主机名IP mac地址。所有三个都用空格分隔,以尝试使用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("(%
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
它会一直打印每个键/值存储在内存中的位置(我想)
我确信这是一个相对容易的修复方法,但我似乎看不到它。正则表达式中没有冒号:
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
如果主机名、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+)"))
然后,
hostname
就是client[1]
,这不是很直观。你说空格是分隔符,然后:line:match((.+)%s+(.+)%s+(.+)”)
太棒了——我知道这是一件小事。您知道我如何将其存储在数组/表中吗。因此,如果我有两个样本行,它可以存储一个列表,并在列表中存储表?@Syn为每行创建一个本地表local tab={}tab.hostName,tab.ip,tab.mac=sampleline:match((%S+)(%S+)(%S+)
,并将它们放入另一个表中。如果您不关心字符串键,那么也可以使用local tab=table.pack(sampleline:match((%S+)(%S+)(+S+)(+S+))
当然可以。