2

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.

1 Answer 1

2

%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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, ([^%d]+)(%d+) is what I'm after. Oh I see, this is my first time using lua properly and the tutorial mentioned it. I'll take it out.
What tutorial? What did it say about it?
You probably mean (.-)(%d+) instead of (.*)(%d+).
@lhf Indeed. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.