Capture data from string using regular expression


#1

Hi,

I want to fetch png from the following String:
image/png

And want to store it into another String

png is not a static it can be anything like jpg

Please help me how I can fetch required string using a regular expression.


#2

Hi Suraj,

Something like the following should extract the png part of image/png:

if (req.http.Content-Type ~ "^(.+)/(.+)$") {
  set req.http.type = re.group.2;
}
# if req.http.Content-Type is "image/png"
# then req.http.type is now "png"

We cover capturing matches in more detail (with examples) in our documentation: https://docs.fastly.com/guides/vcl/vcl-regular-expression-cheat-sheet

Regards, Léon