Site icon JD Bots

How to Use the regex Function in OpenTofu

Card titled The regex Function, labelled OpenTofu Functions, showing regex([0-9]+, Order 42 shipped) and the result 42.

Find text that matches a pattern with OpenTofu’s regex function, read capture groups

regex searches a string with a regular expression, a pattern such as “one or more digits”, and returns the part that matches. With capture groups, it returns each part separately.

Syntax

Syntax

regex(<PATTERN>, <STRING>)

The pattern syntax is listed in regex Function in the OpenTofu® docs.

Prerequisites

Step 1: Try It in tofu console

Open a terminal in any empty folder and start tofu console, which evaluates expressions as you type them:

Terminal

tofu console

Type each expression to see the result. The last one has no match:

tofu console

> regex("[0-9]+", "Order 42 shipped")
"42"
> regex("([0-9]+)-([0-9]+)-([0-9]+)", "Due 2026-11-29")
[
  "2026",
  "11",
  "29",
]
> regex("(?P<year>[0-9]+)-(?P<month>[0-9]+)", "Due 2026-11")
{
  "month" = "11"
  "year" = "2026"
}
> regex("[0-9]+", "No numbers here")
╷
│ Error: Error in function call
│
│   on <console-input> line 1:
│   (source code not available)
│
│ Call to function "regex" failed: pattern did not match any part of the given string.
╵

> exit

Clean Up

Type exit to leave the console. The example creates nothing, so there’s nothing else to remove.

Common Mistakes

MistakeWhat happensDo this instead
Expecting no match to return an empty valueIt stops with pattern did not match any part of the given string.Test first: the docs suggest regexall and checking that its result isn’t empty.
Writing "\d" in a quoted patternThe backslash belongs to the string first.Write "\\d", or a class such as [0-9].

FAQ

Can I check a value without an error?

Wrap it: can(regex(…)) is true when the pattern matches and false when it doesn’t.

Which regular expression syntax does it use?

The one listed in the docs’ table, which includes classes such as [a-z], \\d and anchors ^ and $.

Conclusion

regex(<PATTERN>, <STRING>) returns the matching text, a list of groups or a map of named groups, and stops with an error when nothing matches.

Additional Resources

OpenTofu® is a registered trademark of LF Projects, LLC. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by the OpenTofu project.

Exit mobile version