Quirrel4.41.0

string.regexp.search

Method of regexp, from module "string"
instance.search(str: string, [start: int]): table|null

Finds the first match of the pattern in str at or after start, and returns its span.

Parameters

strstringthe string to search
startintthe index to start searching from; 0 when omitted optional

Return value

A table with begin and end, the bounds of the first match, counted from the start of str and not from start. end is exclusive, so str.slice(m.begin, m.end) is the matched text. null when there is no match at or after start.

Errors

Throws start index out of range when start is negative or greater than str.len(). start equal to str.len() is valid; it searches an empty remainder and finds nothing unless the pattern can match empty.

Throws regexp match aborted: pattern too complex for this input instead of returning null when the search exceeds the engine's backtracking budget, see match for when that happens. A null result never hides an aborted search.

Notes

start also moves where ^ and a word boundary (\b) consider the string to begin: both test relative to start, not to index 0, so an anchored pattern can match starting exactly at start even though the character right before it in str says otherwise. $ still means the true end of str.

Among candidate matches, search returns the leftmost one; among those starting at the same position, quantifiers try the longest match first and alternation tries its branches in the order written.

Example

examples/string/regexp/search.nut
from "string" import regexp

let r = regexp("[a-z]+")
let m = r.search("123 abc 456")
println("m.begin..m.end =", $"{m.begin}..{m.end}")
println("\"123 abc 456\".slice(m.begin, m.end) =", "123 abc 456".slice(m.begin, m.end))

// no match at or after start
println("r.search(\"ABC\", 0) =", r.search("ABC", 0))

// start also moves where ^ considers the string to begin
println("regexp(\"^b\").search(\"ab\", 1) != null =", regexp("^b").search("ab", 1) != null)
Output:
m.begin..m.end = 4..7
"123 abc 456".slice(m.begin, m.end) = abc
r.search("ABC", 0) = null
regexp("^b").search("ab", 1) != null = true

See also

captureFinds the first match of the pattern in str at or after start, and returns the whole match plus every capturing group as an array of spans.
matchReturns whether the pattern matches the whole of str.
regexpclass index