Menu
Coddy logo textTech

string.find()

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

Now that you understand character classes, you can use them with string.find() to search for patterns instead of exact text. This opens up powerful possibilities for text validation and analysis.

The string.find() function works the same way with patterns as it does with literal strings—it returns the position where the pattern first matches:

local text = "User123"
local position = string.find(text, "%d")
print(position)  -- Output: 5

This finds the first digit in the string, which is at position 5. You can also search for the opposite using uppercase character classes:

local code = "ABC123"
local position = string.find(code, "%D")
print(position)  -- Output: 1

Here, %D matches any non-digit character, so it finds the first letter at position 1.

A common validation task is checking if a string starts with a specific pattern. You can use the anchor ^ at the beginning of a pattern to match only at the start of the string:

local username = "player42"
local startsWithLetter = string.find(username, "^%a")

if startsWithLetter then
    print("Valid username")
else
    print("Username must start with a letter")
end

This pattern checks if the string begins with a letter, making it useful for input validation where certain formats are required.

challenge icon

Challenge

Easy

Write a function startsWithLetter that takes text and returns whether the string starts with a letter.

Use string.find() with the anchor ^ and the %a character class to check if the string begins with a letter.

Parameters:

  • text (string): The string to validate

Returns: true if the string starts with a letter, false otherwise (boolean)

Cheat sheet

Use string.find() with character classes to search for patterns in strings. It returns the position where the pattern first matches:

local text = "User123"
local position = string.find(text, "%d")
print(position)  -- Output: 5

Uppercase character classes match the opposite (non-matching characters):

local code = "ABC123"
local position = string.find(code, "%D")
print(position)  -- Output: 1

Use the anchor ^ at the beginning of a pattern to match only at the start of the string:

local username = "player42"
local startsWithLetter = string.find(username, "^%a")

if startsWithLetter then
    print("Valid username")
else
    print("Username must start with a letter")
end

Try it yourself

function startsWithLetter(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