Menu
CoddyTech

Patterns Instead of Regex

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

PHP preg functions use PCRE regular expressions. Lua string patterns are a smaller language, not PCRE with different delimiters. Lua uses %d for digits and parentheses for captures; string.match returns the captures directly or nil when no match exists. Anchors constrain the start and end. PHP preg_match returns a match status and writes captures into a separate array. For these tasks, names and numbers have a narrow ASCII grammar that can be expressed with Lua patterns.

PHP

<?php
preg_match('/^([a-z]+)=(\d+)$/D', "pen=12", $matches);
echo $matches[2], "\n";

Lua

local name,n=("pen=12"):match("^([a-z]+)=(%d+)$")
print(n)

Porting trap

Do not copy PCRE alternation, counted repetitions, or backslash character classes into Lua patterns. Specify ASCII classes such as [a-z] when the task requires them, and validate the entire string before converting captured digits.

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

Practice on your own: Online Lua compiler