Regex Capturing Group in Hugo

810 views Asked by At

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.

2

There are 2 answers

1
Sebastian Korotkiewicz On BEST ANSWER

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"
0
Carson On

Thanks to @modInfo for the inspiration, I decided to expand the answer of replaceRE

by order

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

name group

{{ $my_var := `id="demo2"` }}
{{ $result := replaceRE `id=\"(?P<my_id>.*)\"` "$my_id" $my_var }}
{{ $result }} → "demo2"

more example

{{ $my_var := `<h2 id="#demo+1-3%./2\"><a href="https://www.google.com/"></a></h2>` }}
{{ $id := replaceRE `.*id=\"(?P<my_id>([:#a-z0-9+\-%./\\])*)\">(<a href=\"(?P<my_href>[:#a-z0-9+\-%./\\]*)\">.*)?` "$my_id" $my_var }}
{{ $id }}  → #demo+1-3%./2\
{{ $href := replaceRE `.*id=\"(?P<my_id>([:#a-z0-9+\-%./\\])*)\">(<a href=\"(?P<my_href>[:#a-z0-9+\-%./\\]*)\">.*)?` "$my_href" $my_var }}
{{ $href }}  → https://www.google.com/