Strings & Patterns
Strings are immutable, 1-indexed byte sequences. Lua does not use regular expressions; it has its own, smaller pattern language that covers most everyday cases.
The basics
local s = "Basalt Luak"
print(#s) -- 11, length
print(s:upper()) -- BASALT LUAK
print(s:sub(1, 6)) -- Basalt
print(string.format("%s v%d", "Luak", 5))
s:upper() and string.upper(s) are the same call: every
string carries the string library as its method table, so colon syntax
works directly on string values.
Pattern classes
The building blocks of a Lua pattern:
| Class | Matches |
|---|---|
%a | a letter |
%d | a digit |
%s | whitespace |
%w | a letter or digit |
%p | punctuation |
. | any character |
Uppercasing a class negates it, %A is "not a letter". Quantifiers follow
a class or a literal: * (0 or more, greedy), + (1 or more,
greedy), - (0 or more, shortest match), ? (0 or 1).
^ and $ anchor to the start and end of the string.
find, match, gmatch, gsub
local s = "version 26.5"
local from, to = string.find(s, "%d+%.%d+")
print(from, to) -- 9 13
print(string.match(s, "%d+%.%d+")) -- 26.5
local replaced, count = string.gsub(s, "%d", "#")
print(replaced, count) -- version ##.# 3
for word in string.gmatch("the quick fox", "%a+") do
print(word) -- the / quick / fox, one per iteration
end
Parentheses inside a pattern capture that part of the match. string.match
with a capture returns the captured piece instead of the whole match.
local major, minor = string.match("26.5", "(%d+)%.(%d+)")
print(major, minor) -- 26 5
That covers the everyday language. The full standard library, including every
function on string, is catalogued in
Standard Library once
you are ready to start embedding Lua with Luak.