Menu
Coddy logo textTech

Intro to String Patterns

Part of the Logic & Flow section of Coddy's Lua journey — lesson 36 of 54.

When you used string.gsub() in the previous lesson, you searched for exact text like spaces or specific words. But what if you need to find "any digit" or "any letter" without knowing the exact character? This is where string patterns come in.

String patterns in Lua are a way to describe what kind of text you're looking for, rather than the exact text itself. They're simpler than regular expressions but powerful enough for most text-processing tasks.

Lua provides special codes called character classes that match categories of characters. Here are the most common ones:

%d  -- matches any digit (0-9)
%a  -- matches any letter (a-z, A-Z)
%s  -- matches any whitespace (space, tab, newline)
%w  -- matches any alphanumeric character (letters and digits)
%p  -- matches any punctuation character

Here's how you might use these patterns with string.find() to locate the first digit in a string:

local text = "Room 42 is available"
local position = string.find(text, "%d")
print(position)  -- Output: 6

You can also use uppercase versions of these classes to match the opposite. For example, %D matches any character that is not a digit, and %A matches any character that is not a letter.

challenge icon

Challenge

Easy

Write a function containsDigit that takes text and returns whether the text contains at least one digit.

Use string.find() with the %d character class to check if any digit exists in the string.

Parameters:

  • text (string): The text to check for digits

Returns: true if the text contains at least one digit, false otherwise (boolean)

Cheat sheet

String patterns in Lua describe what kind of text you're looking for, rather than the exact text itself.

Lua provides special codes called character classes that match categories of characters:

%d  -- matches any digit (0-9)
%a  -- matches any letter (a-z, A-Z)
%s  -- matches any whitespace (space, tab, newline)
%w  -- matches any alphanumeric character (letters and digits)
%p  -- matches any punctuation character

You can use uppercase versions to match the opposite. For example, %D matches any character that is not a digit, and %A matches any character that is not a letter.

Using character classes with string.find():

local text = "Room 42 is available"
local position = string.find(text, "%d")
print(position)  -- Output: 6

Try it yourself

function containsDigit(text)
    -- Write code here
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow