Robert Woods
Robert Woods

Reputation: 379

Lua Pattern Matching issue

I'm trying to parse a text file using lua and store the results in two arrays. I thought my pattern would be correct, but this is the first time I've done anything of the sort.

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)

Here's a small snippet of questlist.txt:

If the dead could talk16 Forgotten soul16 The Toothmaul Ploy9 Well-Armed Savages9

And here's a matching snippet of results.txt:

talk 16 soul 16 Ploy 9 Savages 9

What I'm after in results.txt is:

If the dead could talk 16 Forgotten soul 16 The Toothmaul Ploy 9 Well-Armed Savages 9

So my question is, which pattern do I use in order to select all text up to a number?

Thanks for your time.

Upvotes: 2

Views: 97

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 81042

%a matches letters. It does not match spaces.

If you want to match everything up to a sequence of digits you want (.-)(%d+).

If you want to match a leading sequence of non-digits then you want ([^%d]+)(%d+).

That being said if all you want to do is insert a space before a sequence of digits then you can just use line:gsub("%d+", " %0", 1) to do that (the one to only do it for the first match, leave that off to do it for every match on the line).

As an aside I don't think io.input(file) is doing anything useful for you (or what you might expect). It is replacing the default standard input file handle with the file handle file.

Upvotes: 2

Related Questions