Menu
Coddy logo textTech

string.match()

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

While string.find() tells you where a pattern appears in a string, sometimes you need to extract the actual text that matched. This is where string.match() comes in, and it becomes even more powerful when combined with captures.

Captures allow you to mark specific parts of a pattern that you want to extract. You create a capture by wrapping part of your pattern in parentheses (). When string.match() finds a match, it returns the captured text instead of just the position.

Here's a simple example extracting a number from a string:

local text = "Player score: 100"
local number = string.match(text, "%d+")
print(number)  -- Output: 100

The pattern %d+ means "one or more digits." The + is a modifier that matches one or more of the preceding character class, allowing you to capture multi-digit numbers.

You can use captures to extract specific parts of a more complex pattern:

local message = "User: Alice sent a message"
local username = string.match(message, "User: (%a+)")
print(username)  -- Output: Alice

Here, the parentheses around %a+ tell Lua to capture the sequence of letters that comes after "User: ". The rest of the pattern helps locate the right position, but only the captured part is returned.

If your pattern has multiple captures, string.match() returns all of them as separate values, which you can assign to multiple variables at once.

challenge icon

Challenge

Easy

Write a function extractPrice that takes text and returns the price value found in the string.

Use string.match() with a capture pattern to extract the numeric price that appears after the dollar sign. The pattern should capture one or more digits using %d+.

Parameters:

  • text (string): A string containing a price in the format "Price: $XX"

Returns: The numeric price as a string (string)

Cheat sheet

Use string.match() to extract text that matches a pattern:

local text = "Player score: 100"
local number = string.match(text, "%d+")
print(number)  -- Output: 100

The + modifier matches one or more of the preceding character class:

%d+  -- one or more digits
%a+  -- one or more letters

Use parentheses () to create captures that extract specific parts of a pattern:

local message = "User: Alice sent a message"
local username = string.match(message, "User: (%a+)")
print(username)  -- Output: Alice

Multiple captures return separate values:

local var1, var2 = string.match(text, "(pattern1)(pattern2)")

Try it yourself

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