util.string.find

Shared

Searches for a pattern in a string and returns its position


Syntax

local start_at, end_at, ... = util.string.find(
    input,
    pattern,
    start_at = 1,
    plain_text = false
)

Parameters

TypeNameDescription
stringinputString to search in
stringpatternPattern to search for (supports Lua patterns unless plain_text is true)
intstart_atPosition to start searching from - negative counts from end
boolplain_textWhen true - pattern is treated as plain text, not a pattern

Returns

TypeNameDescription
intstart_atStarting index of the match, or nil if not found
intend_atEnding index of the match, or nil if not found
any...Any captured substrings from the pattern

Examples

Find the position of a substring
local s, e = util.string.find("hello world", "world")

core.engine.print("info", s, e) -- 7  11
Find the first occurrence of a character
local pos = util.string.find("hello", "l")

core.engine.print("info", pos) -- 3
Search starting from a specific position
local s, e = util.string.find("hello hello", "hello", 7)

core.engine.print("info", s, e) -- 7  11
Find a pattern match position
local s, e = util.string.find("Price: $25.99", "%d+")

core.engine.print("info", s, e) -- 9  10
Find a pattern and capture a group
local s, e, num = util.string.find("hello 123 world", "(%d+)")

core.engine.print("info", s, e, num) -- 7  9  123
Use plain text search to disable pattern matching
local s, e = util.string.find("Cost: $5.00", "$", 1, true)

core.engine.print("info", s, e) -- 7  7
Find a pattern and capture multiple groups
local s, e, word1, word2 = util.string.find("hello world", "(%a+) (%a+)")

core.engine.print("info", word1, word2) -- hello  world
Search from the end using a negative index
local s, e = util.string.find("hello", "l", -3)

core.engine.print("info", s, e) -- 3  3

On this page