Finds the first match against the target regular expression and tabulates group captures within the match
Agent
Name | Type | Description |
---|---|---|
comparisonString | String |
A string against which the regular expression is matched
|
startIndex | Integer |
An optional character index within the string at which to start matching
|
Array — the matched sub-string and each group capture in tabular form
This method matches the regular expression object against the string passed as its first parameter. It returns an array of tables, each of which contains values indicating the start and end of a matched sub-string found within the parameter string.
Each table contains two keys, begin and end, whose values are the indexes delimiting the sub-string within the parameter string. The array will contain as many of these tables as there are matches. If there are no matches, capture() returns null
not an empty array.
Each capture group in the regular expression is enclosed within parentheses, ()
, and for n capture groups, the returned array will contain n + 1 results. If any particular capture group does not match, the begin and end values will both be set to -1
.
Note that this is different to a zero-length string at some position within the string. For example, the regular expression "(a*)(a)"
gives two matches against "a"
. The first, zero-length one, at index 0 is a match of zero instances of "a"
at the start, which is a legitimate match.
A second, optional parameter may be passed to the method: the index within the passed string at which to begin the search for pattern matches. If this parameter is not provided, the search commences at the start of the string.
// Define the regular expression: | |
// Look for digits one or more times, as a group: (\d+) | |
// Followed by a space, not as a group, ie. no brackets | |
// Followed by any case character one or more times, as a group: ([a-zA-Z]+) | |
// Followed by a punctuation mark, as a group: (\p) | |
local expression = regexp2(@"(\d+) ([a-zA-Z]+)(\p)"); | |
local compareString = "ultimate question 42 answer."; | |
// Generate an array of matches | |
local results = expression.capture(compareString); | |
// Run through the matches if there are any, ie. results != null | |
if (results) { | |
foreach (index, value in results) { | |
// Each value is a table with two keys: 'begin' and 'end' | |
// Get the sub-string from the test string using these indices | |
local subString = compareString.slice(value.begin, value.end) | |
// Print the results | |
server.log(format("Match number[%02d] %s", index + 1, subString)); | |
} | |
} | |
// Displays: | |
// "Match number[01] 42 answer." - the first matched sub-string | |
// "Match number[02] 42" - the digits capture group | |
// "Match number[03] answer" - the alpha characters capture group | |
// "Match number[04] ." - the punctuation caputure group |