Warm tip: This article is reproduced from serverfault.com, please click

Regex Capturing Group in Hugo

发布于 2020-12-12 17:46:01

Recently I wanted to switch my static site generator from Jekyll to Hugo. I really like Hugo, but unfortunately, the usage of some functions often bothered me.


consider the code below,

{{ $my_var := `id="demo"` }}
{{ $my_slice := (findRE `id=\"(.*)\"` $my_var 1) }}
{{ index $my_slice 0 }}

reulst:

id="demo"

expected result

demo

In the above example, I want to get the value of the group.

Please note that what is really needed is a regular representation to get the group, not a tricky use of other functions (such as replace to replace the id=" with a blank or something like that)

regex test website: https://regex101.com/

enter image description here

Please help me, I really spent a lot of time searching but still nothing. I found someone with the same question in Hugo-discourse, but it's been a year and still no answer.

Questioner
Carson
Viewed
0
Sebastian Korotkiewicz 2020-12-14 07:22:43

The easiest way to do this is with replaceRE, where $1 is your group number.

{{ $my_var := `id="demo"` }}
{{ $result := replaceRE `id=\"(.*)\"` "$1" $my_var }}
{{ $result }} → "demo"