Search inside strings, extract parts, and swap text with pattern matching — the tools that turn raw text into useful data.
Strings hold text. Patterns let you search inside that text — find a word, replace a number, pull out a username. Every chat filter, name validator, and save-key parser uses them.
string.find searches a string for a pattern and returns where it starts and ends:
local text = "Player scored 250 points"
local start, finish = string.find(text, "scored")
print(start, finish) -- 8 13
The numbers are character positions (1-indexed). If the pattern isn't found, it returns nil:
local result = string.find(text, "coins")
print(result) -- nil
What does string.find("hello world", "world") return? → two numbers
string.gsub replaces every match of a pattern with something new:
local msg = "I have 5 apples and 3 oranges"
local clean = string.gsub(msg, "apples", "bananas")
print(clean) -- I have 5 bananas and 3 oranges
The original string is unchanged — gsub returns a new string.
print(msg) -- still says apples
This is important: strings are immutable. Every operation produces a new one.
Raw text finds exact matches. But patterns use special codes to match categories of characters:
| Pattern | Matches |
|---|---|
%d | Any digit (0-9) |
%a | Any letter (a-z, A-Z) |
%w | Any letter or digit |
%s | Any whitespace (space, tab) |
. | Any character |
local text = "Player123 scored 456"
local first = string.match(text, "%d+") -- one or more digits
print(first) -- 123
The + means "one or more of the thing before it." Without it, %d only matches a single digit.
What does string.match("abc123xyz", "%a+") return?
Patterns shine when you need to pull structured data out of messy text:
local log = "User204 earned 75 coins"
local user = string.match(log, "(%a+)(%d+)") -- letters then digits
print(user) -- User204
local coins = string.match(log, "(%d+) coins")
print(coins) -- 75
Parentheses () capture the matched — they're how you pull pieces out.
Real-world example — validating a username:
local function isValidName(name)
return string.match(name, "^%a%w+$") ~= nil
end
print(isValidName("Player1")) -- true
print(isValidName("1Player")) -- false (starts with a digit)
The ^ means "must be at the start" and $ means "must be at the end" — together they require the entire string to match.
Extract the number from 'Score: 42' using string.match with a digit pattern. Store it in a variable called score.
local text = "Score: 42"
-- your match line here%.. A bare . matches any character. To find a literal period, escape it: string.find(text, "%.").+ for multiple characters. %d matches one digit. %d+ matches a whole number.string.find("abc123", "%d") finds 1, not 123. Use %d+ to grab all the digits.Next: booleans — yes, no, maybe.