Skip to main content
regexreplace(str, pattern, replace) replaces every match of pattern in str with replace. Uses RE2 regular expression syntax.

Signature

regexreplace(str string, pattern string, replace string) string

Example

Sanitize a git branch name for use as a Kubernetes namespace. Namespaces must be lowercase, alphanumeric, and hyphenated with no leading or trailing hyphens:
variable "branch" {
  description = "Git branch name"
  type        = string
}

computed "namespace" {
  description = "Kubernetes namespace derived from the branch"
  expression  = lower(regexreplace(var.branch, "[^a-z0-9]", "-"))
}

task "deploy-preview" {
  description = "Deploy a preview environment for this branch"
  commands = [
    "kubectl create namespace ${computed.namespace} --dry-run=client -o yaml | kubectl apply -f -",
    "helm upgrade --install preview-${computed.namespace} ./chart --namespace ${computed.namespace}",
  ]
}
feature/My-Branch becomes feature-my-branch.

Notes

  • The pattern must be a valid RE2 expression. RE2 does not support lookahead or backreferences.
  • replace can include $1, $2, etc. to reference capture groups.
  • For simple string substitution without regular expressions, use replace.