🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Parsing with Patterns

Parsing is the job of splitting structured text into its separate fields, using patterns to find each field. A small parser reads a line, captures its fields, and stores them in a table.

One line parses into a key and a value

Two word runs, one on each side of the equals sign, become two captures.

local key, value = string.match("name=ada", "(%w+)=(%w+)")
print(key, value)

gmatch steps through every pair in turn

The loop gives each key and value pair in the order they appear in the text.

for key, value in string.gmatch("name=ada\ncity=paris", "(%w+)=(%w+)") do
  print(key, value)
end

A log line parses into date, level and message

Anchored digit runs take the date, an uppercase run takes the level, and the rest takes the message.

local year, month, day, level, msg = string.match("2026-10-28 ERROR disk full", "^(%d+)-(%d+)-(%d+) (%u+) (.+)")
print(year, month, day, level, msg)

Example

local text = "name=ada\ncity=paris\njob=poet"
local data = {}
local count = 0
for key, value in string.gmatch(text, "(%w+)=(%w+)") do
  data[key] = value
  count = count + 1
end
print(count)
print(data.name, data.city, data.job)

Key points

  • Parser: a loop over matches with a pattern that captures each field turns text into data.
  • Field pattern: (%w+)=(%w+) captures a key before the equals sign and a value after it.
  • Use string.gmatch to step through the matches one at a time, giving the captures of each match in turn.
  • Anchors: ^ pins a log pattern to the start of the line, so the date fields come first.
  • Balanced pairs: %b() can capture a whole parenthesised group as one field, even when it nests.

In this example, the loop steps through every key and value pair in the text and stores each one in a table, counting as it goes. The prints then prove the parser found three fields and read them back by key.

Note

store parsed fields in a table and read them back by key, so the result does not depend on scan order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

For the pattern "(%w+)=(%w+)" matched against "city=paris", what does the second capture hold?