如何在Jinja2中使用正则表达式?

2024-03-29 02:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新晋佳人,到目前为止,我已经可以做我想做的大部分。但是,我需要使用正则表达式,在the documentation或Googles上似乎找不到任何东西。

我想创建一个宏来模拟Javascript中的这种行为:

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

它将删除字符串中的字符,然后用下划线替换空格。我怎么能用Jinja2做这个?


Tags: the字符串jinja2returndocumentationfunctionjavascriptmyfunc
1条回答
网友
1楼 · 发布于 2024-03-29 02:35:45

如果实际上不需要正则表达式,则可以使用名为^{}的现有筛选器。否则,您可以注册一个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

相关问题 更多 >