Skip to main content

Rego's Regular Expression Built-ins

Regular expressions are an important tool for defining and testing patterns, making them useful in a range of policy use cases. Regular expressions enable specifying and enforcing rules on text data, such as validating input formats or extracting relevant substrings for further processing.

Rego's regular expression functions use the RE21 standard, known for its safety and performance features. RE2 avoids slow performance in common cases making it good for use in performance sensitive environments like policy evaluation.

Here is a simple rule based on a regular expression:

email_valid := regex.match(`^[^@]+@[^@]+\.[^@]+$`, "name@example.com")

In this example, the email_valid will be true as the email matches the pattern. Also note that the pattern is defined as a raw string, which is a common practice as it avoids the need to escape special characters2.

While regular expressions are useful in many policies, it's important to consider performance and readability. For simple string operations, such as checking for a substring or performing exact matches, Rego's built-in string matching functions can be faster and easier to read by non-developers.

tip

Check out regex101.com and use the RE2 syntax to test your Rego patterns in a visual way.

Footnotes

  1. Read more about the RE2 syntax

  2. See non-raw Regex Regal rule.