我试图使用lua解析一个文本文件,并将结果存储在两个数组中。我以为我的模式是正确的,但这是我第一次这样做。
fileio.lua
questNames = {}
questLevels = {}
lineNumber = 1
file = io.open("results.txt", "w")
io.input(file)
for line in io.lines("questlist.txt") do
questNames[lineNumber], questLevels[lineNumber]= string.match(line, "(%a+)(%d+)")
lineNumber = lineNumber + 1
end
for i=1,lineNumber do
if (questNames[i] ~= nil and questLevels[i] ~= nil) then
file:write(questNames[i])
file:write(" ")
file:write(questLevels[i])
file:write("\n")
end
end
io.close(file)下面是questlist.txt:的一个小片段
If the dead could talk16 Forgotten soul16 The Toothmaul Ploy9 Well-Armed Savages9
下面是results.txt的匹配片段
talk 16 soul 16 Ploy 9 Savages 9
我在results.txt想要的是:
If the dead could talk 16 Forgotten soul 16 The Toothmaul Ploy 9 Well-Armed Savages 9
因此,我的问题是,我使用哪种模式来选择一个数字以下的所有文本?
耽误您时间,实在对不起。
发布于 2016-01-13 13:30:31
%a与字母匹配。它与空格不匹配。
如果要将所有内容匹配到一个数字序列,则需要(.-)(%d+)。
如果要匹配非数字的前导序列,则需要([^%d]+)(%d+)。
也就是说,如果您想要做的就是在一个数字序列之前插入一个空格,那么您只需要使用line:gsub("%d+", " %0", 1)来完成这个任务(只在第一次匹配时这样做,对于行上的每一次匹配都不需要这样做)。
顺便说一句,我不认为io.input(file)正在为您做任何有用的事情(或者您可能期望的事情)。它正在用文件句柄file替换默认的标准输入文件句柄。
https://stackoverflow.com/questions/34767577
复制相似问题