Regex Invalid Syntax (but actually is valid)

I am trying to find all instances of h2’s in markdown from a front-matter variable using findRE. I have crafted a regex that works on (with the golang filter enabled) but when i plug it into my template it throws an “invalid syntax” error.

here is the regex i’m using:

the fuller context is as follows:
{{ findRE "([^/(\#\#)].*[^/(\\n)])" .Params.body }}

this should take a string like the following:
## **This is a headline**\n

and only return something like this:
**This is a headline**

…but it doesnt. any ideas?

Thanks for the help!

How are you regex’ing against the markdown and not the rendered HTML? Is this something your’e doing with readFile?

Also, just making sure that .Params.body isn’t actually supposed to be .Content instead. Can you provide more surrounding code/intent. Or better, a repo? Also note that you might want to replaceRE rather than findRE if you’re looking to actually replace the matching values.

I’ve been working on regex quite a lot in the past few days and I’ve found that the golang code only works if I make changes to it after I’ve copied it.
What I have tried, which has worked a couple of times, is to replace the quote marks with backticks.

I don’t have a body param in my setup but when I put the below code into my setup, I got all characters in the content.

{{ findRE `([^/(\#\#)].*[^/(\\n)])` .context.Content }}

However, when I input this:

{{ findRE `h2.*?h2` .context.Content }}

it printed out all H2 content into an array for me. Of course, whether this works for you depends on your setup and your content, but this could be one way?


@rdwatters i’m using a json template. it pulls the front matter for each page then i can format how i want the values to be organized in the json file. I am actually using .body because it is scoped within a range (for an array variable) - i don’t want to replace, rather gather all the content that is within the h2 tags.

@eve_crabb that back tic trick is neat! good tip! i ended up chaining the process to markdownify the .body param then searching for the h2 bookends.

thanks guys!


Shouldn’t that “trick” about using backticks instead of quotation marks be mentioned in the documentation of replaceRE and findRE? I’ve just spent half an hour in vain trying to figure out what could be the relevant difference in Golang’s regex engine to not accept my regex until I finally found this thread…:roll_eyes:

Perhaps. Have you submitted a PR to the docs to add said improvement?

Have you submitted a PR to the docs to add said improvement?

Nope, not yet. I first wanted to get the opinion of someone more experienced with Hugo. I figured maybe there’s a good reason why it’s not mentioned in the doc.

So you agree it should be mentioned? Do you know the actual meaning of backticks in Golang templates?