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
regex(<PATTERN>, <STRING>)
<PATTERN>: the regular expression, such as"[0-9]+". Inside a quoted string, write a backslash as\\.<STRING>: the text to search.- The result is a string when the pattern has no groups, a list for unnamed groups
( ), and a map for named groups(?P<name> ).
The pattern syntax is listed in regex Function (opens in a new tab) in the OpenTofu® docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
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:
tofu console
Type each expression to see the result. The last one has no match:
> 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
| Mistake | What happens | Do this instead |
|---|---|---|
| Expecting no match to return an empty value | It 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 pattern | The 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.
0 comments