Back to Blog

Lua with Neowin: String Patterns — %a %d %s %w, Quantifiers, match & gmatch | Episode 25

Sandy LaneSandy Lane

Video: Lua with Neowin: String Patterns — %a %d %s %w, Quantifiers, match & gmatch | Episode 25 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Lua String Patterns: Character Classes, Quantifiers, and Matching

Lua's string pattern system offers a lightweight alternative to regular expressions, enabling powerful text processing with simple syntax. This guide covers key character classes like %a, %d, %s, and %w, quantifiers such as +, *, ?, and demonstrates how to use string.match and string.gmatch for extracting and iterating over matches.

Code

local text = "Email: example123@test.com, Date: 2024-06-15, Price: $45.67"

-- Extract numbers (digits) from the string
for number in text:gmatch("%d+") do
  print("Number found:", number)  -- prints 123, 2024, 06, 15, 45, 67
end

-- Match words (letters only)
for word in text:gmatch("%a+") do
  print("Word:", word)  -- prints Email, example, test, com, Date, Price
end

-- Validate a simple email pattern using captures
local email = text:match("(%w+@%w+%.%a+)")
if email then
  print("Valid email found:", email)  -- prints example123@test.com
end

-- Extract date parts using captures and patterns
local year, month, day = text:match("(%d%d%d%d)%-(%d%d)%-(%d%d)")
if year and month and day then
  print("Date parts:", year, month, day)  -- prints 2024 06 15
end

-- Split CSV-like string by commas and optional spaces
local csv = "apple, banana, cherry, date"
for item in csv:gmatch("%s*([^,]+)%s*") do
  print("CSV item:", item)  -- prints each fruit trimmed
end

Key Points

  • Lua uses special character classes like %a (letters), %d (digits), %s (spaces), and %w (alphanumeric) for pattern matching.
  • Quantifiers +, *, ?, and - control how many times a pattern repeats, enabling flexible matching.
  • string.match returns the first match or captures from a string, while string.gmatch iterates over all matches.
  • Parentheses () capture parts of the match, useful for extracting structured data like dates or emails.
  • Lua patterns are simpler than regex but powerful enough for many common text processing tasks like validation, extraction, and splitting.