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.
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.
- Function notation
- Method notation
extractRegex(value: string, pattern: regexp, group: number | string): string
(value: string).extractRegex(pattern: regexp, group: number | string): string
Arguments
| Name | Type | Required | Description |
|---|---|---|---|
value | string | true | The string to search |
pattern | regexp | true | The regular expression to match. Must be a literal, not a dynamic expression |
group | number | string | false | Which 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
- Function notation
- Method notation
create str from 'GET /api/users 200 OK'
| create status from extractRegex(str, /d+/)
create str from 'GET /api/users 200 OK'
| create status from str.extractRegex(/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
- Function notation
- Method notation
create str from 'name=alice'
| create user from extractRegex(str, /name=(?<user>w+)/, 'user')
create str from 'name=alice'
| create user from str.extractRegex(/name=(?<user>w+)/, 'user')
Example output
{
"str": "name=alice",
"user": "alice"
}