How to output a regex capture group in Nunjucks?

168 Views Asked by At

I am trying to understand how I can access capture groups in a nunjucks template (without using javascript or anything else, just nunjucks) but I can't seem to figure it out.

Take this minimal (non-)working example:

{% set teststring = "lorem ipsum Created: 2016-08-26T15:10:17 Modified: 2017-04-24T11:05:45 BibTeXKey: lorem ipsum" %}
{% set datePattern = r/Created:\s?(\d{4}-\d{2}-\d{2})/gm %}
{{ teststring.match(datePattern)[0] }}

I expected it to output the first capture group (i.e. just the date) but it outputs the entire match:

Created: 2016-08-26

I checked whether the capture group might be available as the second item (index 1) but this modified code outputs nothing.

{% set teststring = "lorem ipsum Created: 2016-08-26T15:10:17 Modified: 2017-04-24T11:05:45 BibTeXKey: lorem ipsum" %}
{% set datePattern = r/Created:\s?(\d{4}-\d{2}-\d{2})/gm %}
{{ teststring.match(datePattern)[1] }}

I found a workaround to get what I want in this specific case by using

{{- teststring.match(datePattern)[0].match(r/\d{4}-\d{2}-\d{2}/g)[0] }}

But this is not ideal and it bugs me that there must be a propper solution.

Where am I going wrong?

0

There are 0 best solutions below