---
title: regsub
summary: null
url: https://www.fastly.com/documentation/reference/vcl/functions/strings/regsub
---

```
STRING regsub(STRING input, REGEX pattern, STRING replacement)
```

**Available in:** all subroutines

Replaces the first occurrence of `pattern` (a Perl-compatible regular expression) in `input` with `replacement`. If no match is found, no replacement is made. Calls to `regsub` do not set `re.group.*`.

> **HINT:** To extract a value from a string (e.g. extract the `.html` from `index.html`), rather than replace a value in a string, consider using `if` instead. [Learn more in VCL best practices](https://www.fastly.com/documentation/guides/vcl/best-practices/#dont-use-regsub-for-data-extraction).

Groups captured in `pattern` can be inserted into the replacement string with \\1 through \\9, which correspond to their `re.group.*` counterparts. Following numeric literals are not interpreted. Captures can also be specified as `\{1}` through `\{19}` which will allow you to specify ones higher than 9. It is advisable to use non-capturing groups with `(?:)` if the sub-pattern is not used in a backreference.

## Errors

This function may fail to make a replacement if the regular expression recurses too heavily. Such a situation may occur with lookahead and lookbehind assertions, or other recursing non-regular expressions. In this case, `fastly.error` is set to `EREGRECUR`.

## Example

The following example deletes the query string portion of the request URL (equivalent to `req.url.path`):

```vcl
set req.url = regsub(req.url, "\?.*$", "");
```

This replaces the last two digits of an HTTP status code to 00 for grouping purposes. Note that the 00 remains as a literal "00" in the substitution:

```vcl
set var.response_code_type = regsub(beresp.status, "^([1-5])..", "\100"); # capture group \1 followed by literal 00
```

This will reverse the first 15 characters of a header:

```vcl
set var.reversed = regsub(req.http.longheader, "(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)", "\{15}\{14}\{13}\{12}\{11}\{10}\9\8\7\6\5\4\3\2\1");
```
