Search code examples
regextemplate-toolkit

template toolkit keep 20 first chrachters in a string


I am trying to remove everything from a string except the first 20 characters. But the regex removes the first 20 and keeps the rest. How can i solve this?

Here is my code:

[% p.name | remove('(.{20})', '$1') %]

I have also tried this:

[% p.name.replace('(.{20})', '$1')) %]

Solution

  • Your regex won't match the string whose length is less than 20.

    Use:

    [% p.name.replace('(?<=.{20}).*', '')) %]
    

    Or:

    [% p.name.replace('(.{0,20}).*', '$1')) %]