Pattern Matching

Jul 1, 2023  │  m. Jul 2, 2023 by Gleb Buzin

Lua does not have regular expressions. Instead it has pattern matching. The string.gmatch function will take an input string and a pattern. This pattern describes on what to actually get back. This function will return a function which is actually an iterator.

Simple matching

for char in ("abc"):gmatch "." do
    print(char)
end

for match in ("#afdde6"):gmatch "%x%x" do
    print("#" .. match)
end
a
b
c
#af
#dd
#e6

Capture groups

local s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
    print("key: " .. k .. ", value: " .. v)
end
key: from, value: world
key: to, value: Lua

Character classes

Character classMatching section
%aletters (A-Z, a-z)
%ccontrol characters (\n, \t, \r, …)
%ddigits (0-9)
%llower-case letter (a-z)
%ppunctuation characters (!, ?, &, …)
%sspace characters
%uupper-case letters
%walphanumeric characters (A-Z, a-z, 0-9)
%xhexadecimal digits (\3, \4, …)
%zthe character with representation 0
.Matches any character

Any upper-case version of those classes represents the complement of the class. For instance, %D will match any non-digit character sequence.



Next: Math