Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 4: Strings and patterns

Objectives: LO-4.1, LO-4.2, LO-4.3, LO-4.4
Prerequisites: Module 3
Time: about 10 hours: 3 for this reading, 2 for Lab 4, 2 for the practice, and 3 for PA2, which follows this module

This module covers Lua’s string library: cutting and formatting text, searching it with Lua’s patterns, building long strings efficiently, and handling text that isn’t plain ASCII. Patterns look like regular expressions, but they are a smaller language with a few features regular expressions lack, so this module spends time on what they can’t do and what to write instead. Module 1 introduced string literals, .., and #; this module builds on them.

Strings and the string library

A Lua string is an immutable sequence of bytes. No function changes a string in place: every function that “changes” one returns a new string, and the original stays as it was.

The string table holds the library’s functions, and every string can call them as methods. A method call, written with a colon, passes the value before the colon as the first argument, so these two lines do the same thing:

local s = "hello"
print(string.upper(s))     --> HELLO
print(s:upper())           --> HELLO

This works because all strings share a metatable whose __index field is the string table, so looking up upper on a string finds string.upper; module 7 explains metatables. A literal needs parentheses before the colon: ("ab"):rep(3) works, but "ab":rep(3) is a syntax error.

FunctionResultExample
s:len()The length in bytes, the same as #s("hello"):len() is 5
s:sub(i, j)The bytes from position i to j("hello"):sub(2, 4) is "ell"
s:upper(), s:lower()A string with letters converted according to the current locale("MiXeD"):lower() is "mixed"
s:rep(n, sep)n copies, with sep between them("ab"):rep(3, "-") is "ab-ab-ab"
s:reverse()The bytes in reverse order("abc"):reverse() is "cba"
s:byte(i, j)The numeric codes of the bytes("Hi"):byte(1, 2) is 72, 105
string.char(...)The string of the given byte codesstring.char(72, 105) is "Hi"

Positions and negative indices

Positions count from 1, like table indices. A negative position counts from the end: -1 is the last byte, -2 the one before it. sub clamps positions that fall outside the string instead of failing, and gives the empty string when i comes after j:

local s = "hello"
print(s:sub(-3))         --> llo     (the last three bytes)
print(s:sub(-3, -2))     --> ll
print(s:sub(2))          --> ello    (j defaults to -1, the end)
print(s:sub(4, 2))       -->         (the empty string: 4 comes after 2)
print(s:sub(-100, 2))    --> he      (-100 is clamped to 1)

string.format

string.format(fmt, ...) builds a string from a template, following the rules of C’s printf. Each conversion, a % followed by a letter, takes the next argument:

ConversionFormatsExampleResult
%dAn integerstring.format("%d", 42)42
%5d, %-5d, %05dWidth 5: right-aligned, left-aligned, zero-paddedstring.format("%05d", 42)00042
%x, %XAn integer in hexadecimalstring.format("%x", 255)ff
%.2fA float with two decimalsstring.format("%.2f", 3.14159)3.14
%e, %gScientific, or the shorter of %e and %fstring.format("%g", 1e20)1e+20
%s, %10s, %-10sAny value, through tostring, with an optional widthstring.format("[%-4s]", "ab")[ab ]
%qA value written as Lua source, so it can be read backstring.format("%q", 'say "hi"')"say \"hi\""
%%A literal percent signstring.format("%d%%", 50)50%

Three rules catch people out:

tonumber(s, base) reads a number in any base from 2 to 36, and ignores spaces around it: tonumber("ff", 16) is 255, tonumber(" 42 ") is 42, and tonumber("4 2") is nil.

Patterns

A pattern describes a set of strings, and the functions in the next section search text for the parts that match it. A pattern is itself a string, in which most characters match themselves and a few have special meanings.

Character classes

A character class matches one byte from a set. The table uses Lua’s default C locale.

ClassMatches
.Any byte
%aA letter
%dA decimal digit
%l, %uA lowercase or uppercase letter
%sA whitespace character: space, tab, newline, and the like
%wA letter or digit
%pA punctuation character
%xA hexadecimal digit
%cA control character

An uppercase class such as %D matches the opposite set. For example, %D matches any byte outside 0 through 9. In the default locale, %a recognizes the ASCII letters A–Z and a–z. The section on UTF-8 below shows how to read characters that span several bytes.

A set in square brackets matches one character from a set you define. [aeiou] matches a vowel, [0-9a-f] a digit or a letter from a to f, and [%w_] a letter, digit, or underscore. A ^ right after the [ inverts the set: [^,] matches any character except a comma.

Quantifiers

A quantifier after a class says how many times it repeats:

QuantifierRepeats the classExampleMatches
+One or more times, as many as possible%d+2026 in "in 2026"
*Zero or more times, as many as possible%s*Any run of spaces, even an empty one
-Zero or more times, as few as possible<.-><a> in "<a><b>"
?Zero or one timecolou?rcolor and colour

* and + are greedy: they take as much as they can and still let the rest of the pattern match, so <.*> matches all of "<a><b>". - is lazy: it takes as little as it can, so <.-> stops at the first >. A quantifier applies to one class only; there is no way to repeat a longer piece of a pattern.

Anchors and magic characters

A ^ at the start of a pattern anchors the match to the start of the text, and a $ at the end anchors it to the end. ^%d+$ matches a string made only of digits, and nothing else.

The characters ^ $ ( ) % . [ ] * + - ? are magic: they have special meanings. To match one of them literally, put % before it. %. matches a dot and %% a percent sign. Forgetting the % is a common bug: in a pattern, . matches any character, and a - right after a class is a quantifier, so %d%d-%d%d doesn’t match 12-34. Write %- for every hyphen you mean, even where Lua would read a bare - as one.

Captures

Parentheses around part of a pattern capture the text it matched, and the search functions return each capture as a separate value:

local key, value = ("width=800"):match("(%w+)=(%w+)")
print(key, value)              --> width  800

Three more kinds of capture exist:

Balanced pairs and frontiers

Two items have no equivalent in most regular-expression languages:

Searching and replacing

Four functions use patterns:

FunctionReturns
s:find(pattern, init, plain)The start and end positions of the first match, then its captures; or nil
s:match(pattern, init)The captures of the first match, or the whole match if the pattern has none; or nil
s:gmatch(pattern)An iterator over every match, for the generic for
s:gsub(pattern, repl, n)A new string with the matches replaced, and the number of replacements

init says where to start searching, and may be negative. find’s fourth argument, plain, turns patterns off: s:find(".", 1, true) finds a literal dot. Use it when you search for text that a user typed, which may hold magic characters.

gmatch returns an iterator, so it goes in a generic for. With captures, each pass gets them; without, each pass gets the whole match:

for word in ("The quick, brown fox."):gmatch("%a+") do
  io.write(word, "|")              --> The|quick|brown|fox|
end

for k, v in ("a=1, b=2"):gmatch("(%w+)=(%w+)") do
  print(k, v)                      --> a 1, then b 2
end

In gmatch, a ^ at the start of the pattern isn’t an anchor, because an anchored pattern could match only once. Lua 5.4 treats it as a literal ^, so ("aaa"):gmatch("^a") finds nothing.

gsub

gsub replaces every match, or the first n. Its replacement, repl, can be one of three things:

-- a string, in which %1 to %9 stand for the captures and %0 for the whole match
print(("hello world"):gsub("(%w+)", "<%1>"))          --> <hello> <world>  2

-- a table, looked up with the first capture as the key
local vars = { name = "Ada", age = 36 }
print(("$name is $age"):gsub("%$(%w+)", vars))        --> Ada is 36  2

-- a function, called with the captures
print(("1 2 3"):gsub("%d", function(d) return d * 2 end))   --> 2 4 6  3

When the table has no entry, or the function returns nil or false, gsub keeps the original match: ("$name and $x"):gsub("%$(%w+)", vars) gives "Ada and $x". A % in a replacement string must be written %%; a lone one stops with invalid use of '%' in replacement string.

gsub returns two values, and that surprises people. print(s:gsub("a", "b")) prints the count too, and return s:gsub(...) returns both. Wrap the call in parentheses to keep only the string:

local function no_vowels(s)
  return (s:gsub("[aeiou]", ""))
end
print(no_vowels("banana"))         --> bnn

Patterns are not regular expressions

Lua patterns look like the regular expressions of Python, JavaScript, or grep, but they are a smaller language. Lua’s designers kept them small: in Lua 5.4.8, the whole pattern matcher, with find, match, gmatch, and gsub, is under 600 lines of C in the file lstrlib.c. The differences:

Regular expressionsLua patterns
\d, \w, \s, and \.%d, %w, %s, and %.: the escape character is %
*?, a lazy star-
a|b, alternationNot available
(ab)+, a quantifier on a groupNot available: quantifiers apply to one class
x{2,4}, a counted repeatNot available: write xxx?x?
(?:…), (?=…), and other groups and lookaroundsNot available
Nothing standard for balanced pairs%b()
\b, a word boundary%f[%w] and %f[%W], frontiers, which work with any set

The missing alternation is the one you will miss most. Rewrite it as Lua code: match the general shape with a pattern, then test the part that varies. For example, the regular expression \.(jpg|png|gif)$ matches file names with one of three extensions:

local image_types = { jpg = true, png = true, gif = true }

local function is_image(name)
  local ext = name:match("%.(%a+)$")     -- the general shape: a dot, letters, the end
  return ext ~= nil and image_types[ext:lower()] == true
end

print(is_image("cat.png"), is_image("notes.txt"), is_image("png"))   --> true  false  false

The table of extensions is a set, from module 3, and testing it is O(1)O(1). When the alternatives are whole patterns rather than words, try each pattern in turn. When a format needs alternation everywhere, or nesting deeper than %b handles, a parser is the better tool, which the next section introduces.

Beyond patterns: LPeg

When patterns aren’t enough, the usual next step is LPeg, a library by Roberto Ierusalimschy, one of Lua’s authors, for parsing expression grammars (PEGs): a way to describe a format by rules that try their alternatives in order. LPeg is written in C, so it runs in the standalone lua, but not in the notebooks’ %%lua cells, which can’t load C libraries. Install it with LuaRocks, as setting up your environment shows, and run these examples as scripts.

An LPeg pattern is a Lua value that you build with functions and operators, not a string. A string or a number where LPeg expects a pattern becomes one, so lpeg.P("a") * "b" works:

LPegMatchesAs a regular expression
lpeg.P("cat")The text catcat
lpeg.R("az")One character in a range[a-z]
lpeg.S("+-")One character from a set[+-]
1Any one character.
p1 * p2p1, then p2p1p2
p1 + p2p1, or else p2p1|p2
p^0, p^1, and p^-1Zero or more, one or more, and at most one pp*, p+, and p?
p1 - p2p1, where p2 doesn’t match(?!p2)p1
p * -1p, then the end of the textp$
lpeg.C(p)p, captured as a string(p)

The regular expression ^(cat|dog)s?$, which the previous section had to rewrite as code, is one LPeg pattern:

local lpeg = require("lpeg")
local P = lpeg.P

local pet = (P("cat") + P("dog")) * P("s")^-1 * -1
print(pet:match("cats"), pet:match("dog"), pet:match("catss"))   --> 5  4  nil

match returns the position just after the match, or nil. A pattern matches only at the start of the text, as if it began with ^.

Captures turn what matched into values. p / f passes p’s captures to the function f and captures what it returns, and lpeg.Ct(p) collects p’s captures into a table. This pattern reads a list of numbers, with a quantifier on a whole group, which Lua patterns can’t do:

local R, S, C, Ct = lpeg.R, lpeg.S, lpeg.C, lpeg.Ct

local space = S(" \t")^0
local number = C(R("09")^1) / tonumber                -- capture the digits, then convert them
local list = Ct(space * number * (space * "," * space * number)^0 * space) * -1

local t = list:match("1, 22,333 ")
print(#t, t[1] + t[2] + t[3])                         --> 3  356
print(list:match("1,,2"))                             --> nil

A grammar is a table of rules that can refer to each other, and to themselves, with lpeg.V("name"); its first entry names the rule to match. That handles nesting of any depth. %b() knows one kind of bracket: ("([a)]"):match("%b()") returns ([a). A grammar checks two kinds, nested in any order:

local V = lpeg.V

local brackets = P({
  "pair",                                                 -- the rule to match first
  pair = "(" * V("inner") * ")" + "[" * V("inner") * "]",
  inner = ((1 - S("()[]")) + V("pair"))^0,                -- non-brackets, or nested pairs
})
print(brackets:match("([a]())"), brackets:match("([a)]"))   --> 8  nil

One difference from regular expressions catches everyone. LPeg’s + is ordered choice: it tries p1, and tries p2 only if p1 fails. Once p1 has matched, a later failure doesn’t go back to try p2, as a regular expression’s | would:

print(((P("a") + "ab") * "c"):match("abc"))   --> nil: "a" matched, then "c" failed at "b"
print(((P("ab") + "a") * "c"):match("abc"))   --> 4

Put the longer alternative first. LPeg also ships the re module, which writes the same patterns in a syntax closer to regular expressions: re.match("cats", "('cat' / 'dog') 's'? !.") returns 5, where / is ordered choice and !. means “no character follows”.

Use patterns for one field or one line, and LPeg when a format needs alternation, quantified groups, or nesting, such as a configuration language, a query syntax, or JSON. The cost is a C library that everyone who runs your program must install too.

Building long strings

Because strings are immutable, s = s .. piece builds a new string and copies all of s into it. In a loop that appends n pieces, the copies add up to about n2/2n^2/2 pieces’ worth, which is O(n2)O(n^2). Collect the pieces in a list and join them once with table.concat, which copies each piece once:

local parts = {}
for i = 1, 3 do
  parts[#parts + 1] = string.format("line %d", i)
end
local text = table.concat(parts, "\n")
print(text)                        --> line 1, line 2, and line 3, on three lines

On an Intel Core i7-11800H, in Lua 5.4.8 through lupa 2.8, building a 400,000-byte string from 40,000 pieces of 10 bytes took 0.59 s with .. in a loop, and 1.7 ms with table.concat. Lab 4 repeats the measurement. A few .. in one expression, such as a .. ", " .. b, are fine: Lua joins them in one step.

Text that isn’t ASCII: UTF-8

Lua strings hold bytes. UTF-8 encodes a Unicode code point in one to four bytes. For example, the single code point é takes two bytes. A reader can also see one letter where the text contains two code points, as with an e followed by a combining accent. Try these operations in Lua’s default C locale.

local word = "héllo"
print(#word)                 --> 6: five characters, six bytes
print(word:upper())          --> HéLLO: upper changes only ASCII letters
print(word:match("%a+"))     --> h: %a matches only ASCII letters
print(utf8.len(word:sub(1, 2))) --> nil  2 (the slice ends inside é)

s:reverse() reverses bytes, so it scrambles any character longer than one byte, and s:sub can cut one in half. Use the utf8 library to work with code points.

FunctionResultExample
utf8.len(s)The number of code points, or nil and the starting byte of the first invalid sequenceutf8.len("héllo") is 5
utf8.char(...)The string of the given code pointsutf8.char(72, 233) is "Hé"
utf8.codepoint(s, i, j)The code points of the characters that start between bytes i and jutf8.codepoint("é") is 233
utf8.codes(s)An iterator over each character’s byte position and code pointSee below
utf8.offset(s, n)The byte position where character n startsutf8.offset("hé€x", 3) is 4
utf8.charpatternA pattern that matches one code point in an already valid UTF-8 strings:gmatch(utf8.charpattern)
for position, code in utf8.codes("hé€") do
  io.write(position, ":", code, " ")      --> 1:104 2:233 4:8364
end

€ starts at byte 4 because é took bytes 2 and 3. utf8.codes stops with invalid UTF-8 code on malformed input. To check text before walking it, call utf8.len. On failure its second result points to the start of the invalid sequence. On success, decide whether the code-point count answers your question. For example, utf8.len("é") is 1 and utf8.len("e\u{301}") is 2, although both display as one letter.

Common misconceptions

BeliefWhat Lua doesExample that breaks it
String functions change the stringThey return a new ones:upper() leaves s as it was
"ab":rep(3) worksA literal needs parenthesesIt is a syntax error; write ("ab"):rep(3)
. in a pattern matches a dotIt matches any character("a.b"):gsub(".", "-") gives ---
Captures of digits are numbersCaptures are strings("x=10"):match("=(%d+)") + 1 works, but == 10 is false
return s:gsub(...) returns the stringIt returns the string and the countprint(("aaa"):gsub("a", "b")) prints bbb 3
Patterns support | like regular expressionsThere is no alternationMatch the shape, then test a set
LPeg’s + works like a regular expression’s |It is ordered: once the first option matches, the second is never tried((P("a") + "ab") * "c"):match("abc") is nil
^ anchors a gmatch patternIt matches a literal ^ there("aaa"):gmatch("^a") finds nothing
s = s .. piece in a loop is fineIt is O(n2)O(n^2)40,000 pieces took 0.59 s instead of 1.7 ms
#s counts charactersIt counts bytes#"héllo" is 6
%a and upper handle any letterIn the default C locale, they recognize ASCII letters("héllo"):match("%a+") is "h"

Summary

Self-check

  1. What do ("lua"):rep(2, " "), ("pattern"):sub(-4, -2), and string.format("%-6s|%3d", "ab", 7) give?

    Answer

    "lua lua", "ter", and "ab | 7". Position -4 is the t of tern, and -2 the r; %-6s pads ab on the right to six characters, and %3d pads 7 on the left to three.

  2. Write a pattern that matches a time such as 08:15:02 and captures the hours, minutes, and seconds.

    Answer

    (%d%d):(%d%d):(%d%d). The captures are strings, such as "08"; pass them to tonumber to compute with them.

  3. What do ("<b>bold</b>"):match("<(.*)>") and ("<b>bold</b>"):match("<(.-)>") give, and why do they differ?

    Answer

    "b>bold</b" and "b". .* is greedy, so it runs to the last >; .- is lazy, so it stops at the first.

  4. How would you match lines that start with GET or HEAD, which a regular expression writes as ^(GET|HEAD) ?

    Answer

    Capture the word with ^(%u+) , then test it against a set: local methods = { GET = true, HEAD = true } and methods[word]. Lua patterns have no alternation.

  5. name holds "Zoë". What are #name and utf8.len(name), and what does name:reverse() give?

    Answer

    4 and 3: ë takes two bytes. reverse reverses the four bytes, which splits ë into its two bytes in the wrong order, so the result isn’t valid UTF-8 and utf8.len of it is nil.

Further reading