util.string.match

Shared

Searches for the first match of a pattern and returns captures


Syntax

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

Parameters

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

Returns

TypeNameDescription
any | nil...Captured strings or nil if no match is found

Examples

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

On this page