Vital.sandbox
String

string.match

Shared

Searches for the first match of a pattern and returns captures


Syntax

local ... = string.match(input, pattern, start_at = 1)

Parameters

TypeNameDescription
stringinputString to be searched in
stringpatternLua pattern to match
intstart_atPosition to start searching from - negative counts from end

Returns

TypeNameDescription
... / nil...Captured strings or nil if no match is found

Examples

Match and return an entire pattern
local result = string.match("hello 123", "%d+")

engine.print("info", result) --'123'
Match with a single capture group
local num = string.match("Price: $25", "%$(%d+)")

engine.print("info", num) --'25'
Extract multiple captures at once
local word1, word2 = string.match("hello world", "(%a+) (%a+)")

engine.print("info", word1, word2) --'hello  world'
Extract user and domain from an email
local user, domain = string.match("john@example.com", "(.+)@(.+)")

engine.print("info", user) --'john'
engine.print("info", domain) --'example.com'
Match starting from a specific position
local result = string.match("hello hello", "hello", 7)

engine.print("info", result) --'hello'
Extract a number from a string
local num = string.match("Temperature: 25°C", "%d+")

engine.print("info", num) --'25'
Extract text from within quotes
local text = 'name="John Doe"'
local value = string.match(text, '"(.-)"')

engine.print("info", value) --'John Doe'
Parse URL into protocol, domain, and path
local url = "https://example.com/path"
local protocol, domain, path = string.match(url, "(.-)://([^/]+)(.+)")

engine.print("info", protocol) --'https'
engine.print("info", domain) --'example.com'
engine.print("info", path) --'/path'
Return nil when no match is found
local result = string.match("hello", "%d+")

engine.print("info", result) --nil
Extract a semantic version number
local version = string.match("v1.2.3", "v(%d+%.%d+%.%d+)")

engine.print("info", version) --'1.2.3'
Match the first word in a string
local word = string.match("  hello world  ", "%a+")

engine.print("info", word) --'hello'
Extract a hexadecimal color code
local color = string.match("color: #FF5733", "#(%x+)")

engine.print("info", color) --'FF5733'
Validate and extract a username
local text = "user123"
local name = string.match(text, "^(%a+%d+)$")

if name then
    engine.print("info", "Valid username:", name)
end
Extract a key-value pair
local key, value = string.match("setting=enabled", "(.-)=(.*)")

engine.print("info", key, value) --'setting  enabled'
Capture the position after a match
local text = "hello world"
local pos = string.match(text, "world()")

engine.print("info", pos) --12

On this page