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 entire pattern
local result = string.match("hello 123", "%d+")
engine.print(result) --123
--Match with single capture
local num = string.match("Price: $25", "%$(%d+)")
engine.print(num) --25
--Multiple captures
local word1, word2 = string.match("hello world", "(%a+) (%a+)")
engine.print(word1, word2) --hello  world
--Extract email parts
local user, domain = string.match("john@example.com", "(.+)@(.+)")
engine.print(user) --john
engine.print(domain) --example.com
--Match with starting position
local result = string.match("hello hello", "hello", 7)
engine.print(result) --hello
--Extract number from string
local num = string.match("Temperature: 25°C", "%d+")
engine.print(num) --25
--Extract quoted text
local text = 'name="John Doe"'
local value = string.match(text, '"(.-)"')
engine.print(value) --John Doe
--Match URL components
local url = "https://example.com/path"
local protocol, domain, path = string.match(url, "(.-)://([^/]+)(.+)")
engine.print(protocol) --https
engine.print(domain) --example.com
engine.print(path) --/path
--No match returns nil
local result = string.match("hello", "%d+")
engine.print(result) --nil
--Extract version number
local version = string.match("v1.2.3", "v(%d+%.%d+%.%d+)")
engine.print(version) --1.2.3
--Match first word
local word = string.match("  hello world  ", "%a+")
engine.print(word) --hello
--Extract hexadecimal color
local color = string.match("color: #FF5733", "#(%x+)")
engine.print(color) --FF5733
--Validate and extract
local text = "user123"
local name = string.match(text, "^(%a+%d+)$")
if name then
    engine.print("Valid username:", name)
end
--Extract key-value pair
local key, value = string.match("setting=enabled", "(.-)=(.*)")
engine.print(key, value) --setting  enabled
--Capture position (empty capture)
local text = "hello world"
local pos = string.match(text, "world()")
engine.print(pos) --12

On this page