In the future, you may wish to consider using the regex_findall_index
filter. It can be used to extract precisely what you want from a string.
Templating - Regular Expressions
Here’s an example containing several numbers. We wish to extract only the numbers ending with %
. The numbers can be with or without a decimal separator (period).
{% set value = "The 4th attempt made on 2019-04-02 produced the following result 89.75% which is higher than the previous values of 78.55%, 65.0%, and 50% concentration." %}
This will find all four matching numbers (89.75, 78.55, 65.0, and 50) and report the first one.
{{ value | regex_findall_index('(\d+\.?\d+)%') }}
The four matching numbers are indexed from 0 to 3 so if I want the third one (index=2) I would use this:
{{ value | regex_findall_index('(\d+\.?\d+)%', index=2) }}
The tricky part is learning how to use regular expressions (regex). It’s a powerful string-matching language that can be challenging to master. This interactive regex tester helps one to learn the syntax: regex101
I’ll explain the expression I used so you can see how powerful regex can be:
-
Everything between ( )
is a capture group, meaning that’s what will be extracted and reported. You can have several capture groups within an expression.
-
( )%
means whatever is found in the capture group must be immediately followed by a literal per cent character.
-
\d
means to match a number.
-
\d+
means to match one or more numbers.
-
\.
means match a period.
-
\.?
means optionally match a period.
Here is how it looks in the Template Editor: