如何在Jinja2中使用正则表达式? [英] How do I use regular expressions in Jinja2?

查看:278
本文介绍了如何在Jinja2中使用正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Jinja2的新手,到目前为止,我已经能够完成我想做的大部分事情.但是,我需要使用正则表达式,并且在文档中找不到任何内容,或者在Google上.

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.

我想创建一个模仿Javascript中此行为的宏:

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

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

将删除字符串中的字符,然后用下划线替换空格.如何使用Jinja2做到这一点?

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

推荐答案

已有一个名为 replace ,如果您实际上不需要正则表达式,可以使用它.否则,您可以注册自定义过滤器:

{# 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

这篇关于如何在Jinja2中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆