Menu
CoddyTech

Patterns Instead of Regex

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

Godot offers RegEx for regular expressions. Lua's built-in string matching uses a smaller pattern language with different syntax. For an ASCII inventory line, ^([a-z]+)=([0-9]+)$ works in both examples, capturing the label and digits. The anchors require the entire line to match. Lua string.match returns the captures directly, or nil on failure; Godot returns a RegExMatch object whose captured groups are read with get_string. Convert the captured digits before displaying their numeric value to remove leading zeroes. Do not assume that every Godot regular expression has a direct Lua-pattern translation.

GDScript 4

extends SceneTree
func _init():
    var regex = RegEx.new()
    regex.compile("^([a-z]+)=([0-9]+)$")
    var found = regex.search("potion=007")
    if found != null:
        print(found.get_string(1) + ":" + str(int(found.get_string(2))))
    else:
        print("invalid")
    quit()

Lua 5.1

local name, digits = string.match("potion=007", "^([a-z]+)=([0-9]+)$")
if name then
  print(name .. ":" .. tonumber(digits))
else
  print("invalid")
end

Porting trap

Lua patterns use %d for a digit class, not the regex escape \d. The explicit ASCII class [0-9] avoids that syntax difference here.

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 GDScript Developers

Practice on your own: Online Lua compiler