38

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?

Jason
  • 51,583
  • 38
  • 133
  • 185

1 Answers1

50

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
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 14
    yeah this is the way i ended up going, unfortunately. it's dumb you can't use regex in jinja2 – Jason Oct 10 '12 at 17:48
  • 1
    hey, man! You say it is a non-optimal implementation, could you ellaborate on what would look like the optimal one? – Elias Dorneles Feb 09 '13 at 14:13
  • 2
    @elias - since `find` is compiled each time it is used by `re.sub` if this was used as a filter in a large loop it could *potentially* be a bottleneck. If that were the case you could either add a keyword arg to the filter (`cache`) and compile and store `find` args when `cache` was set to `True` - or you could just compile and cache all `find` arguments and choose an ejection strategy that best suites your application. – Sean Vieira Feb 09 '13 at 14:32
  • 3
    @SeanVieira (Sorry for the late comment) It's worth noting that Python's re module caches compiled regexes automatically since at least as far back as 1.5.2 (and the cache size was raised to 100 in 2.0). Depending on how many regexes are in play in the app, the benefit of a cache might already be covered. – mikenerone Nov 13 '17 at 17:13