groups()

Extracts capture group matches from a string using a regular expression and returns them as an array.

Syntax

groups(STR_EXPR, REGEX_PATTERN)

Parameters

STR_EXPR
The source string or expression to extract from.
REGEX_PATTERN
A regular expression string containing capture groups. Parts enclosed in parentheses () are capture groups.

Description

The groups() function converts STR_EXPR to a string and repeatedly matches REGEX_PATTERN against it, returning an array of all capture group values from all matches in order. If no matches are found, returns null. If any argument is null, returns null.

Group indices start at 1. The full match (group(0)) is not included; only capture groups are extracted.

Error codes

N/A

Usage examples

To prepare the WEB_APACHE_SAMPLE table used in these examples, refer to Preparing sample data.

  1. Extracting path segments from a URI

    table limit=5 WEB_APACHE_SAMPLE | eval result = groups(uri, "/([^/]+)") | fields uri, result
    | # result: an array containing each path segment of the URI
    
  2. Extracting browser name and version from User-Agent

    table limit=5 WEB_APACHE_SAMPLE | eval result = groups(agent, "(\\w+)/([\\.\\d]+)") | fields agent, result
    | # result: an array containing the browser name and version strings
    
  3. NULL input

    json "{'val': null}" | eval result = groups(val, "([a-z]+)")
    | # result: null
    

Compatibility

The groups() function has been available since before Sonar 4.0.