---
page_title: regex_replace function reference
description: >-
  The `regex_replace` function matches and replaces all occurrences of a substring with a replacement string. 
---

⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️
> [!IMPORTANT]  
> **Documentation Update:** Product documentation previously located in `/website` has moved to the [`hashicorp/web-unified-docs`](https://github.com/hashicorp/web-unified-docs) repository, where all product documentation is now centralized. Please make contributions directly to `web-unified-docs`, since changes to `/website` in this repository will not appear on developer.hashicorp.com.
⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️

# `regex_replace` Function

`regex_replace` searches a given string for another given substring, and
replaces each occurrence with a given replacement string. The substring
argument can be a valid regular expression or a string.

```hcl
regex_replace(string, substring, replacement)
```

`substring` should not be wrapped in forward slashes, it is always treated as a
regular expression. The `replacement` string can incorporate captured strings
from the input by using an `$n` or `${n}` sequence, where `n` is the index or
name of a capture group.

## Examples

```shell-session
> regex_replace("hello world", "world", "everybody")
hello everybody


> regex_replace("hello world", "w.*d", "everybody")
hello everybody

> regex_replace("-ab-axxb-", "a(x*)b", "$1W")
---

> regex_replace("-ab-axxb-", "a(x*)b", "${1}W")
-W-xxW-
```

## Related Functions

- [`replace`](/packer/docs/templates/hcl_templates/functions/string/replace) searches a given string for another given
  substring, and replaces all occurrences with a given replacement string.
