Quirrel4.41.0

string.regexp.constructor

Method of regexp, from module "string"
constructor(pattern: string): instance

Compiles pattern into a reusable regexp instance.

Parameters

patternstringthe pattern to compile, in this engine's own syntax (see Notes)

Return value

A compiled pattern. Call match, search or capture on it any number of times; the same instance can be reused for every call.

Errors

Throws a description of the problem when pattern does not parse, for example unterminated character class, expected paren or quantifier value too large. Throws backreferences are not supported for \1-\9, and lazy quantifiers are not supported for *?, +? or ??: both are syntax this engine recognizes and rejects by design, not syntax it fails to parse. An excessively large or deeply nested pattern throws pattern too complex or pattern exceeds maximum allowed nesting depth while compiling, before anything is matched.

Notes

This is not PCRE; it is a small classic-regex engine. What it supports:

\1-\9 and \l/\u mean something different, or nothing special, inside a [...] class: there \1 is just the digit 1 and \b is just the letter b, since backreferences and word boundaries make no sense inside a class.

Example

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

let r = regexp("[a-zA-Z]+[0-9]*")
println("r.match(\"item42\") =", r.match("item42"))
println("r.match(\"42item\") =", r.match("42item"))

// the same compiled pattern is reused across calls
println("r.match(\"abc\") =", r.match("abc"))

try {
  regexp("[a-z") // unterminated character class
} catch (e) {
  println("regexp(\"[a-z\") throws:", e)
}
Output:
r.match("item42") = true
r.match("42item") = false
r.match("abc") = true
regexp("[a-z") throws: unterminated character class

See also

matchReturns whether the pattern matches the whole of str.
searchFinds the first match of the pattern in str at or after start, and returns its span.
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.
regexpclass index