Hugo templating inside RegEx?

I’m trying to experiment creating the highlight shortcode in a probably hacky way and it involves using RegEx.

Here’s the shortcode:

{{ $lineCount := sub (len (findRE "\n" .Inner)) 1 }}
<table>
  <tbody>
    <tr>
      <td>
        <pre>
          <code>
            {{- range seq 1 $lineCount -}}
              <span id = "{{- . -}}">
                <a href = "#">
                  {{- . -}}
                </a>
              </span>
            {{- end -}}
          </code>
        </pre>
      </td>
      <td>
        {{- range seq 1 $lineCount -}}
          {{- $currentLine := sub . 1 -}}
          {{- highlight (delimit (findRE "\A(?:^.*$\n){{{- $currentLine -}}}\K^.*$" $.Inner 1) "") ($.Get 0) "" -}}
        {{- end -}}
      </td>
    </tr>
  </tbody>
</table>

The idea being I’m counting total number of line breaks in the .Inner of the shortcode, and then using RegEx to match the content of the line number and highlight it individually. The RegEx seems to work perfectly in testing, tested here: Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript.

I’m doing this to try to generate random IDs for multiple shortcodes on the same page (the current example is being prepared just as a demo).

The RegEx seems to work fine to do the trick, however if I add any Hugo stuff in it, I get an expected syntax error. Is it possible to use Hugo variables, etc. in RegEx? I tried a printf statement too, but that didn’t work either.

Also, is anyone anticipating any problems if I go ahead in this manner for the highlight to work?

You have escape sequence issues. Use a raw string for the pattern by using backticks instead of double-quotes.

findRE `\A(?:^.*$\n){{{- $currentLine -}}}\K^.*$` $.Inner 1

I did not know that there’s a difference between double-quotes and back-ticks. Thanks for the tip. However, now I get the error: error calling findRE: error parsing regexp: invalid escape sequence: `\K and if I remove the back-slash before K, I get no matches.

\K is not supported by the Go regexp engine. See the syntax guide.

Oh, I see. Sadly, this way won’t work then. Thanks for the help!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.