How do I use regular expressions in Jinja2?

There is an already existing filter called replace that you can use if you don’t actually need a regular expression. Otherwise, you can register a custom filter:

{# Replace method #}
{{my_str|replace("some text", "")|replace(" ", "_")}}

 

# Custom filter method
def regex_replace(s, find, replace):
    """A non-optimal implementation of a regex filter"""
    return re.sub(find, replace, s)

jinja_environment.filters['regex_replace'] = regex_replace

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)