regsub

STRINGregsubSTRINGinputSTRINGpatternSTRINGreplacement

Available inall 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.

Groups captured in pattern can be inserted into the replacement string with \1 through \9, which correspond to their re.group.* counterparts.

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):

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:

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

Try it out

regsub is used in the following code examples. Examples apply VCL to real-world use cases and can be deployed as they are, or adapted for your own service. See the full list of code examples for more inspiration.

Click RUN on a sample below to provision a Fastly service, execute the code on Fastly, and see how the function behaves.

Convert timestamps to relative times like '2 hours ago'

Generate relative time datelines at the Edge instead of in the browser or at origin. Better caching, faster rendering, fewer reflows.

Search and replace in strings

Use regular expression substitution functions to map paths, strip extraneous slashes, and more.

User contributed notes

BETA

Do you see an error in this page? Do you have an interesting use case, example or edge case people should know about? Share your knowledge and help people who are reading this page! (Comments are moderated; for support, please contact Fastly support)