Menu
CoddyTech

Parsing with Lua Patterns

Lesson 28 of 48 in Coddy's Lua for Go Developers course.

Go regexp uses regular expressions and returns a slice of submatches or nil for no match. Lua patterns are a smaller language using percent classes and returning captures directly. Anchor the accepted grammar and check failure before reading captured values. Do not copy regular-expression escapes or features into a Lua pattern unchanged.

Go

package main
import ("fmt"; "regexp")

func main(){
m:=regexp.MustCompile(`^([a-z]+)=([0-9]+)$`).FindStringSubmatch("pen=12"); fmt.Println(m[2])
}

Lua

local name, digits = ("pen=12"):match("^([a-z]+)=([0-9]+)$")
if name then
  print(digits)
else
  print("invalid")
end

Porting trap

Use Lua pattern syntax and handle nil when matching fails.

challenge icon

Challenge

Easy

Input is one line. Accept exactly one or more lowercase ASCII letters, an equals sign, and one or more digits. Return name:number with leading numeric zeroes removed, or invalid for any malformed line.

Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Try it yourself

local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for Go Developers

Practice on your own: Online Lua compiler