Skip to main content

Regular expressions in DataPrime

Regular expressions let you find text by its shape instead of its exact value. With one pattern you can keep every log line that mentions an error code, pull a user name out of a message, or mask every phone number in a field.

A regular expression (regex) is a pattern that describes text. For example, \d+ matches one or more digits, so it finds 404 in status 404 returned. DataPrime supports two dialects of regular expressions: the Ruby dialect, written as /.../, and the RE2 dialect, written as re2'...'.

Where you can use regular expressions​

WhereWhat the regular expression does
matchesTests whether a string contains a match. Use it in filter to keep matching documents.
extract with regexp or multi_regexpCaptures parts of a string into new fields.
regexpSplitPartsSplits a string on each match and returns one part.
arraySplitSplits a string on each match and returns all the parts as an array.
redactReplaces each match with a replacement string.

Every place in the table accepts both dialects.

Regular expression basics​

These building blocks work the same way in both dialects:

PatternMatchesExample
abcThe exact text abcerror matches an error occurred
.Any single character except a newlinea.c matches abc and a-c
\dA digit\d\d\d matches 404
\sA whitespace characteruser\s+id matches user id
[abc]One of the listed characters[ew]arn matches earn and warn
[^abc]Any character except the listed ones[^0-9] matches any non-digit
*, +, ?The previous item zero or more times, one or more times, or zero or one timewarn(ing)? matches warn and warning
{n}The previous item exactly n times\d{4} matches 2026
a|bEither a or berror|warn matches error and warn
(...)A group, which you can repeat or capture(ab)+ matches abab
^, $The start or end of the text^GET matches only text that starts with GET

matches returns true when the regular expression matches anywhere in the string. To require a match of the whole value, anchor it with ^ and $.

Choose a dialect​

The two dialects share most of their syntax but run on different engines:

  • Ruby dialect (/.../) uses Ruby regular expression syntax. It supports advanced features such as lookarounds and backreferences.
  • RE2 dialect (re2'...') uses RE2, a regular expression engine that matches in time proportional to the length of the input. A pattern can never make a query run extremely slowly through catastrophic backtracking. In exchange, RE2 does not support lookarounds, backreferences, and a few other features.

The same filter in each dialect keeps documents whose level field contains error, warn, or warning in any letter case:

source logs
| filter matches(level, /error|warn(ing)?/i)
source logs
| filter matches(level, re2'(?i)error|warn(ing)?')

For documents with level values ERROR, Warning, and info, both queries keep the first two.

Use RE2 when predictable query time matters, for example on large datasets or with patterns that other people write. Use the Ruby dialect when you need a feature RE2 does not support.

Write an RE2 regular expression​

Prefix the regular expression with re2 and wrap it in single quotes. The RE2 engine receives the text as you write it, so \d, \s, and other escapes keep their usual meaning. Two details differ from the /.../ literal:

  • To include a single quote, escape it as \'.
  • A forward slash needs no escaping.

Set flags inline​

The Ruby dialect takes flags as a suffix after the closing slash, as in /error/i. The re2'...' literal has no suffix. Put the flags at the start of the regular expression in a (?flags) group:

FlagEffect
iMatches letters regardless of case.
mMulti-line mode. ^ and $ match at every line boundary.
sThe dot (.) also matches a newline.
UQuantifiers are lazy by default.

Combine flags in one group, for example re2'(?is)error.*timeout'.

Capture named groups​

Name a capture group with (?<name>...). RE2 also accepts (?P<name>...), but (?<name>...) works in both dialects, so prefer it. The extract command with the regexp extractor stores each named group as a field:

source logs
| extract message into user_data using
regexp(re2'(?i)user (?<user>[a-z]+) has logged in')

For the input { "message": "User Chris has logged in" }, the query adds the following field:

{
"user_data": {
"user": "Chris"
}
}

Syntax RE2 does not support​

RE2 gives up a few features to guarantee linear-time matching. A regular expression that uses any of these is rejected as invalid:

  • Backreferences, such as \1 or \k<name>
  • Lookarounds: (?=...), (?!...), (?<=...), and (?<!...)
  • Recursive patterns, such as (?R)
  • Possessive quantifiers, such as *+, ++, and ?+
  • Atomic groups, (?>...)
  • The extended-mode flag (?x)

Differences between the dialects​

Regular expressions that both dialects accept can still behave differently. Check these differences before you move a regular expression from one dialect to the other:

TopicRuby dialect (/.../)RE2 dialect (re2'...')
^ and $Match at every line boundary.Match only at the start and end of the whole string. Add (?m) to match at line boundaries.
Dot matches newlineThe m flag turns it on.The s flag turns it on. m means multi-line.
FlagsA suffix after the closing slash, as in /error/i.An inline group at the start, as in (?i).
[[:alpha:]] and \bUnicode-aware.ASCII only. For example, ([[:alpha:]]+) captures caf from café. Use \p{L} to match any letter.
\sMatches a vertical tab.Does not match a vertical tab.
Property classes such as \p{Alpha}Accepted.Invalid. Use a Unicode class such as \p{L} or \p{Lu}.
Warning

The m flag has opposite meanings in the two dialects. Copying (?m) or a trailing m from a Ruby regular expression into an RE2 one changes it from "dot matches newline" to "multi-line anchors". Use (?s) for the dot behavior.

Convert a Ruby regular expression to RE2​

  1. Replace /regex/ with re2'regex' and escape any single quote as \'.
  2. Move each flag from the suffix into a (?flags) group, and translate it: i stays (?i), and m (dot matches newline) becomes (?s). The x flag has no RE2 equivalent, so rewrite the regular expression without it.
  3. When the regular expression relies on ^ or $ matching at each line, add (?m).
  4. Rewrite backreferences and lookarounds. RE2 reports them as invalid.
  5. Run the query against sample data and compare the results with the Ruby version.

Troubleshooting​

If the query fails with ruby regular expressions are not supported, use re2'...' instead, the Ruby dialect is turned off where the expression runs. Rewrite the regular expression as re2'...'.

Last updated on