2

I have the following regular expression in Varnish configuration language

^/abc/([a-zA-Z0-9\-\ ]*)-([0-9]+)

Now , I want fetch the value $2 part(i.e [0-9]+) of regular expression in Varnish.

How can I get this value?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Nithish
  • 369
  • 1
  • 8
  • 20

1 Answers1

2

You may use regsub in this case:

set req.url = regsub(req.url, "^/abc/([a-zA-Z0-9 -]*)-([0-9]+).*", "\2");

You match the whole string, capture the part you need, and replace with the appropriate backreference.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • it is not working in varnish4+ version it is giving error as : Symbol not found: 're.group.2' (expected type STRING_LIST) – Nithish May 25 '17 at 12:51
  • @nr23: Did you add `import std;` at the top? – Wiktor Stribiżew May 25 '17 at 12:52
  • What is your input? Is it a string? – Wiktor Stribiżew May 25 '17 at 12:57
  • url like: www.example.com/abc/def-123 – Nithish May 25 '17 at 12:58
  • I checked it again and see that `regsub` should still work as expected. Also, could you please confirm if `$2` works? Like `if (req.url ~ "^/abc/([a-zA-Z0-9 -]*)-([0-9]+)") { set req.http.Thing-I-Want = $2; }` – Wiktor Stribiżew May 25 '17 at 13:14
  • i have one doubt in varnish storage process, i have specified file location to store cache in file system but when i removed that file it is still giving varnish request as hit why it is happening ???? – Nithish May 26 '17 at 16:10
  • @nr23: No idea, but cache related issues are usually solved after a system restart. Sorry, it is already another question, not related to this one. – Wiktor Stribiżew May 26 '17 at 20:37
  • Late to the party here, but I believe it should be `set req.http.Thing-I-Want = regsub(req.url, "^/abc/([a-zA-Z0-9 -]*)-([0-9]+)", "\2")` – ErnestV Dec 19 '21 at 17:07