🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Pattern Character Classes

A character class is a pattern piece that matches one character of a named kind, such as a letter or a digit. Classes let one short pattern match any member of a kind, not one fixed character.

One class matches one character of its kind

Each class below finds the first character of its kind in the string.

print(string.match("a1", "%a"))
print(string.match("a1", "%d"))
print(string.match("a1", "%w"))
print(string.match("9f", "%x"))
print(string.match("aB", "%l"))
print(string.match("aB", "%u"))
print(string.match("ab!", "%p"))

Uppercase classes match the opposite kind

An uppercase letter negates the class, and find gives positions for invisible characters.

print(string.match("1a", "%A"))
print(string.match("a1", "%D"))
print(string.match("aB", "%U"))
print(string.match("Ab", "%L"))
print(string.match("f?", "%X"))
print(string.match("!a", "%P"))
local s, e = string.find(" a", "%S")
print(s, e)
local t, u = string.find("a ", "%W")
print(t, u)
local v, w = string.find("a\nb", "%c")
print(v, w)

Sets match one character from a list or range

A set lists its members, a range covers them with a dash, and a caret negates the set.

print(string.match("xyzabc", "[abc]"))
print(string.match("123abc", "[a-z]"))
print(string.match("ABC", "[A-Z]"))
print(string.match("a1", "[0-9]"))
print(string.match("hello", "[aeiou]"))
print(string.match("abcx", "[^abc]"))

Example

local letter, digit = string.match("K7", "(%u)(%d)")
print(letter, digit)
print(string.match("K7", "[A-Z]"))
print(string.match("K7", "[0-9]"))

Key points

  • Classes: %a matches one letter, %d matches one digit, and %s matches one whitespace character.
  • More classes: %w matches one letter or digit, and %x matches one hexadecimal digit.
  • Case classes: %l matches one lowercase letter, and %u matches one uppercase letter.
  • Mark classes: %p matches one punctuation mark, and %c matches one control character.
  • Negation: an uppercase class letter means the opposite kind, so %A matches one character that is not a letter.
  • Sets: [abc] matches one character from the listed characters, and [a-z] matches one character in the range.
  • Set negation: [^abc] matches one character that is not in the listed set.

In this example, the pattern has two captures, one class for an uppercase letter and one for a digit, so match returns K and 7 separately. The two set matches then confirm the same facts one character at a time, with a range for uppercase letters and a range for digits.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which pattern matches one lowercase letter?