Skip to main content

Rego Built-in Function: contains

contains is a commonly used Rego built-in function that checks if a string contains a substring. The function returns true if the string contains the substring and false otherwise.

Some examples of policy use cases where contains might be used include:

  • Simple validation, such as checking if an email contains a @ symbol.
  • Checking if user input contains restricted words or phrases for content moderation.

If you're looking to check a string that's expected to be at the start or end of a value, you might be better served by one of the following functions:

  • Starts With: Checks if a string starts with a specified prefix.
  • Any Prefix Match: Checks if a string starts with any of the specified prefixes.
  • Ends With: Checks if a string ends with a specified suffix.
  • Any Suffix Match: Checks if a string ends with any of the specified suffixes.

These are safer and potentially faster too.


contains only operates on strings, if you're looking to check for the presence of a value in a list you cannot use this function.


If you're looking for the Rego keyword contains for building multi-value rules, you can read about it in the keywords section.


Simple email validation

In the example that follows, contains is used to test if the @ symbol is contained in the supplied email address. This can be useful as a first check on raw user data.

# policy.rego
example1 if contains("", "@")

example2 if contains("bob[at]", "@")

example3 if contains(, "@")

Run in OPA Playground

RuleOutput ValueNotes
example3Depends on user input

Keyword checking for content moderation

The contains function is also useful for checking user text for keywords, certain keywords might not be allowed. In this example, reasons will be a list of the banned words found in the input.message.

# policy.rego
banned_words := {"hate", "kill"}

reasons contains word if {
some word in banned_words
contains(input.message, word)
# input.json
"message": "i hate apples"

Run in OPA Playground

RuleOutput Value