replaceRE gives syntax error

{{ $item | replaceRE "^\((\S{3,7})? *Windows\)$" "$1" }}

where $item is a string and equals (x32 Windows) or (x64 Windows) or (x32/x64 Windows).

I checked validity of RegEx syntax on by choosing Golang.

I get error invalid syntax. Please help.

You either need to escape the backslashes in the regex like so:

replaceRE "^\\((\\S{3,7})? *Windows\\)$" "$1"

or use backticks instead of quotes like so:

replaceRE `^\((\S{3,7})? *Windows\)$` `$1`

Thanks @alexandros. I tried
replaceRE `^\((\S{3,7})? *Windows\)$` `$1` and
replaceRE "^\\((\\S{3,7})? *Windows\\)$" "$1" and both worked.

But I don’t understand what’s the difference between ` and " while specifying parameters in Hugo function (here replaceRE). Also, I was using \ to escape ( and ), so why should I escape \ in itself?

Apparently the backtick is a special way to quote regular expression strings without Go templates complaining. I discovered this feature on my own. It is not documented as far as I know.

Maybe @moorereason knows more.

Regarding the need to escape the backslash again this is due to the Go templates package that Hugo uses. There are several threads in the forum about this quirk, if you want to look it up search the forum for invalid syntax

Personally I use backticks when possible since it is cleaner than escaping backslashes.

1 Like

There are two layers of interpretation here. One is Go template strings and the other is regular expressions.

For Go strings, the Go spec is helpful. See Literal strings use the back tick. Interpreted strings use the double quote.

Escaping the parenthesis is needed for the regexp pattern itself and has little to do with Go.

As @alexandros said, I almost always use literal strings when building regexp patterns in Go or Hugo.


I see. Interesting. Maybe in Hugo Docs, the example given should use ` rather than ", or atleast a note in this regard…? Is it fine if I submit a pull request?

Pull requests to the Docs are always welcome.