HCL Language – 22 – Regular Expressions in HCL

Regular Expressions in HCL

HCL (HashiCorp Configuration Language) is a powerful configuration language used in various HashiCorp tools like Terraform and Packer. While HCL primarily focuses on defining infrastructure and configurations, it also supports regular expressions. In this guide, we will explore how to work with regular expressions in HCL for pattern matching and data validation.

Pattern Matching in HCL

Regular expressions are used in HCL to match patterns within strings. This can be particularly useful for tasks like validating input data or extracting specific information from strings.

Using the regex Function

HCL provides a built-in function called regex that allows you to match a regular expression against a string. Here’s an example of how to use it:


variable "email" {
  type    = string
  default = "user@example.com"
}

output "validEmail" {
  value = regex("^\\w+@\\w+\\.\\w+", var.email)
}
    

In this example, we’re using a regular expression to validate if the content of the email variable matches a typical email format. The regex function returns true if there’s a match.

Capturing Groups

Regular expressions can also be used to capture specific parts of a string by defining groups. In HCL, you can access these captured groups using the regexall function.

Using the regexall Function

Here’s an example of how to capture specific parts of a string using the regexall function:


variable "data" {
  type    = string
  default = "Name: John, Age: 30"
}

output "name" {
  value = regexall("Name: (\\w+), Age: (\\d+)", var.data)[0][1]
}

output "age" {
  value = regexall("Name: (\\w+), Age: (\\d+)", var.data)[0][2]
}
    

In this example, we use capturing groups to extract the name and age from the data variable. The regexall function returns a list of matches, and we access the desired values using indices.

Replacing with Regular Expressions

Regular expressions in HCL can also be used for string replacement. This is particularly handy for modifying strings based on patterns.

Using the replace Function

The replace function allows you to replace parts of a string that match a regular expression:


variable "sentence" {
  type    = string
  default = "Hello, World!"
}

output "greeting" {
  value = replace(var.sentence, "^Hello", "Hi")
}
    

In this example, we replace the “Hello” at the beginning of the sentence variable with “Hi.”

Summary

Regular expressions are a powerful tool for pattern matching, validation, and string manipulation in HCL. With functions like regexregexall, and replace, you can handle a wide range of tasks within your configuration files. Whether you’re validating user inputs or extracting specific data from strings, regular expressions provide a versatile way to work with text data in HCL.