How to Use Regex Function in Terraform: Syntax and Examples
In Terraform, the
regex() function checks if a string matches a regular expression pattern and returns the matching substring. Use regex("pattern", string) to extract the first match or regexall("pattern", string) to get all matches as a list.Syntax
The regex() function takes two arguments: a regular expression pattern and the string to search. It returns the first substring that matches the pattern. If no match is found, it causes an error. The regexall() function returns a list of all matching substrings or an empty list if none match.
- pattern: The regular expression to match.
- string: The text to search within.
terraform
regex(pattern, string) regexall(pattern, string)
Example
This example shows how to extract the first number from a string using regex() and all numbers using regexall(). It demonstrates pattern matching and outputting results.
terraform
variable "input_string" { default = "User123 has 456 points and 789 credits" } output "first_number" { value = regex("\\d+", var.input_string) } output "all_numbers" { value = regexall("\\d+", var.input_string) }
Output
first_number = "123"
all_numbers = ["123", "456", "789"]
Common Pitfalls
Common mistakes include:
- Using
regex()when no match exists, which causes an error. - Not escaping special characters in the pattern properly.
- Confusing
regex()(returns first match) withregexall()(returns all matches).
Always test your regex patterns and handle cases where matches might not exist.
terraform
/* Wrong: regex() with no match causes error */ output "no_match_error" { value = regex("abc", "def") } /* Right: use regexall() to safely get matches or empty list */ output "safe_no_match" { value = regexall("abc", "def") }
Output
safe_no_match = []
Quick Reference
| Function | Description | Return Type | Behavior if No Match |
|---|---|---|---|
| regex(pattern, string) | Returns first substring matching pattern | string | Error if no match |
| regexall(pattern, string) | Returns list of all matching substrings | list(string) | Empty list if no match |
Key Takeaways
Use regex(pattern, string) to get the first match substring in Terraform.
Use regexall(pattern, string) to get all matches as a list safely.
regex() errors if no match is found; regexall() returns an empty list instead.
Escape special characters in regex patterns properly with double backslashes.
Test regex patterns to avoid runtime errors in Terraform configurations.