Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use regular expressions in Jinja2?

Tags:

regex

jinja2

I'm new to Jinja2 and so far I've been able to do most of what I want. However, I need to use regular expressions and I can't seem to find anything anywhere in the documentation or on teh Googles.

I'd like to create a macro that mimics the behavior of this in Javascript:

function myFunc(str) {
    return str.replace(/someregexhere/, '').replace(' ', '_');
}

which will remove characters in a string and then replace spaces with underscores. How can I do this with Jinja2?

like image 743
Jason Avatar asked Oct 09 '12 00:10

Jason


People also ask

How do you use Jinja filters?

Overview of Jinja2 filtersWe apply filters by placing pipe symbol | after the variable followed by name of the filter. Filters can change the look and format of the source data, or even generate new data derived from the input values.


1 Answers

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
like image 51
Sean Vieira Avatar answered Sep 26 '22 22:09

Sean Vieira