Quirrel4.41.0

string.regexp.capture

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

Finds 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.

Parameters

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

Return value

An array of tables shaped like search's result (begin and end). Index 0 is always the whole match. Index i, for i from 1, is the i-th capturing group counted by where its ( opens, not where it closes: in ((a)b) the outer group is index 1 and the inner one is index 2. A group that took no part in the match - for example one inside an alternative that did not run - is reported as the span 0..0, relative to the very start of str, not null and not relative to start or to the match. null when there is no match at or after start.

Errors

The same as search: start index out of range for a start outside [0, str.len()], and regexp match aborted: pattern too complex for this input instead of returning null when the search exceeds the backtracking budget.

Notes

subexpcount gives the length of the returned array in advance, once str matches: one for the whole match, plus one per capturing group. (?:...) groups are not capturing and add nothing to either.

Example

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

let caps = regexp("(\\d+)-(\\d+)").capture("id 12-34 end")
println("caps.len() =", caps.len())                      // whole match + 2 groups
foreach (i, c in caps)
  println($"{i}: {c.begin}..{c.end}")

// a group inside an alternative that did not run reports an empty span
// at the very start of the string, not null
let alt = regexp("(a)|(b)").capture("xb")
println("alt[1].begin..alt[1].end =", $"{alt[1].begin}..{alt[1].end}")
Output:
caps.len() = 3
0: 3..8
1: 3..5
2: 6..8
alt[1].begin..alt[1].end = 0..0

See also

searchFinds the first match of the pattern in str at or after start, and returns its span.
subexpcountReturns how many sub-expressions the pattern has.
regexpclass index