Skip to main content

extractRegex

Description

Return the first substring of a string that matches a regular expression, or null when the pattern does not match.

The optional group argument selects what the match returns: 0, the default, returns the whole match, a positive number returns that positional capture group, and a string returns the capture group with that name.

Note

Captured values are always strings. Use `convert` when a value needs another datatype.

Syntax

Like many functions in DataPrime, extractRegex supports two notations, function and method. These interchangeable forms allow flexibility in how you structure expressions.

extractRegex(value: string, pattern: regexp, group: number | string): string

Arguments

NameTypeRequiredDescription
valuestringtrueThe string to search
patternregexptrueThe regular expression to match. Must be a literal, not a dynamic expression
groupnumber | stringfalseWhich part of the match to return: 0 (default) for the whole match, N for the N-th positional capture group, or a name for a named capture group. Must be a literal

Example 1

Use case: Pull the status code out of a request line

Without a group argument, the whole match is returned. A pattern that finds no match returns null, which is how you tell an empty match apart from no match at all.

Example query

create str from 'GET /api/users 200 OK'
| create status from extractRegex(str, /d+/)

Example output

{
"str": "GET /api/users 200 OK",
"status": "200"
}

Example 2

Use case: Return one capture group instead of the whole match

Pass a capture group name to return just that part. The same works positionally: extractRegex(str, /name=(w+)/, 1) returns alice, while group 0 returns name=alice.

Example query

create str from 'name=alice'
| create user from extractRegex(str, /name=(?<user>w+)/, 'user')

Example output

{
"str": "name=alice",
"user": "alice"
}
Last updated on
Was this page helpful?