Jinja2 has no regular expression support built in. That single fact explains most of the confusion around this topic: people copy a snippet using regex_search, it fails with a template error, and they assume they have made a syntax mistake. They have not. Those filters come from Ansible, not from Jinja, and if you are running plain Jinja2 in Flask, FastAPI, Django templates using Jinja, or a static site generator, you have to add them yourself.
Quick answer: In Ansible, use the built in regex_search, regex_replace and regex_findall filters plus the match and search tests. In standalone Jinja2 there are none, so register your own filters from Python’s re module on the environment before rendering. Never build regular expressions from user input inside a template.
Below are both routes, with working code, plus the compiled pattern trick that keeps templates fast when a filter runs inside a loop. If you are still finding your way around the syntax, our guide to unpacking multiple variables in a Jinja2 loop covers the basics.
Which situation are you in?
| Environment | Regex available? | What to use |
|---|---|---|
| Ansible playbooks and roles | Yes | regex_search, regex_replace, regex_findall, match, search |
| Flask, FastAPI, Quart | No | Register custom filters on the Jinja environment |
| Pelican, Nikola, MkDocs macros | No | Same, usually via a plugin hook |
| Salt states | Partly | Salt adds its own regex_search and regex_match |
| Django templates | No | Different engine entirely, write a template tag |
In Ansible: the three filters and two tests
Ansible ships regex support because playbooks constantly need to pull a version number out of command output. The filters map directly onto Python functions, and Ansible documents each one, including regex_search.
# extract the first match, returns None if nothing matches
kernel: "{{ uname_output | regex_search('[0-9]+.[0-9]+.[0-9]+') }}"
# capture a group and return only that group
major: "{{ release | regex_search('^([0-9]+).', '1') | first }}"
# replace, with backreferences written as 1
normalised: "{{ hostname | regex_replace('^(web|api)-([0-9]+)$', '2.1') }}"
# every match as a list
all_ips: "{{ config_text | regex_findall('d{1,3}(?:.d{1,3}){3}') }}"
# tests, used in when: and conditionals
when: interface_name is match('^eth[0-9]+$')
when: log_line is search('timeout')The distinction between match and search is the same as in Python. match anchors at the start of the string, search looks anywhere in it. Getting these the wrong way round is the most common bug in Ansible conditionals.
Warning: YAML eats backslashes before Jinja ever sees them. Always quote regular expressions, and prefer single quotes so that escape sequences pass through untouched. A pattern that works on the command line and fails in a playbook is nearly always a quoting problem, not a regex problem.
In standalone Jinja2: register your own filters
This is about fifteen lines and it is the part every tutorial skips. Add the filters to the environment once, at start up, and every template gets them.
import re
from jinja2 import Environment, FileSystemLoader
def regex_search(value, pattern, group=0, ignorecase=False):
flags = re.IGNORECASE if ignorecase else 0
m = re.search(pattern, str(value), flags)
return m.group(group) if m else None
def regex_replace(value, pattern, replacement, count=0, ignorecase=False):
flags = re.IGNORECASE if ignorecase else 0
return re.sub(pattern, replacement, str(value), count=count, flags=flags)
def regex_findall(value, pattern, ignorecase=False):
flags = re.IGNORECASE if ignorecase else 0
return re.findall(pattern, str(value), flags)
env = Environment(loader=FileSystemLoader("templates"), autoescape=True)
env.filters["regex_search"] = regex_search
env.filters["regex_replace"] = regex_replace
env.filters["regex_findall"] = regex_findall
env.tests["matches"] = lambda v, p: re.match(p, str(v)) is not None
env.tests["contains_pattern"] = lambda v, p: re.search(p, str(v)) is not NoneOn Flask the environment already exists, so you attach to it rather than creating one.
from flask import Flask
app = Flask(__name__)
app.jinja_env.filters["regex_search"] = regex_search
app.jinja_env.filters["regex_replace"] = regex_replace
# or, more idiomatically
@app.template_filter("slugify")
def slugify(value):
out = re.sub(r"[^a-z0-9]+", "-", str(value).lower())
return out.strip("-")Now the template reads exactly like the Ansible version.
{% raw %}<h1>{{ post.title | slugify }}</h1>
{% if user.email is contains_pattern('@example.(com|org)' ) %}
<p>Internal user</p>
{% endif %}
{% for line in log_lines %}
{% set ts = line | regex_search('^[(.*?)]', 1) %}
{% if ts %}<li>{{ ts }}</li>{% endif %}
{% endfor %}{% endraw %}Tip: Compile patterns you use in loops. re.compile at module level, then reference the compiled object inside the filter, removes the pattern parsing from every iteration. On a page rendering a few thousand rows it is a measurable difference.
Do the work in Python, not in the template
The most useful advice about regular expressions in Jinja is to use fewer of them. A template is a presentation layer. Every pattern you push into it is logic your tests cannot easily reach, your type checker cannot see, and the next person reading the template has to decode.
Prefer passing prepared values into the context. If a view needs the release number extracted from a string, extract it in the view and pass release_major to the template. Reserve template side regex for genuinely presentational transformations such as highlighting a search term. The Jinja documentation on custom filters is the reference for registering them properly.
Note: Never build a pattern from user supplied text. A crafted expression can trigger catastrophic backtracking and hang the worker process, which is a denial of service with no exploit code required. If you must match on user input, escape it with re.escape or use plain string containment instead.
Troubleshooting
No filter named regex_search. You are on plain Jinja2 and have not registered it. There is nothing to import from Jinja itself.
Backreferences render as literal text. In Python replacement strings a group is 1. Writing $1 inserts those two characters literally, which is the habit people bring from JavaScript and PHP.
The filter returns nothing and the page shows None. A failed search returns None, which Jinja renders as the word None. Chain | default('', true) to keep the output clean. The related question of checking whether a variable exists at all is worth reading alongside this.
It works in a shell and fails in the template. Escaping. Print the pattern itself into the page once and look at what actually arrived.
Matching is case sensitive when you did not want it. Pass an ignorecase argument through to the flags, as in the implementation above, rather than wrapping the whole pattern in a case insensitive group.
Frequently asked questions
Does Jinja2 support regular expressions out of the box?
No. Core Jinja2 ships no regex filters or tests. The familiar regex_search and regex_replace filters are provided by Ansible, which extends Jinja with its own filter set, and Salt adds a similar pair of its own.
How do I add a regex filter to Flask?
Define a Python function that calls re, then attach it with app.jinja_env.filters["name"] = func or decorate it with @app.template_filter("name"). Register at start up so every template and every blueprint sees it.
What is the difference between match and search in Ansible?
match anchors the pattern at the beginning of the string, so it only succeeds if the string starts with the pattern. search finds the pattern anywhere in the string. If a conditional unexpectedly fails, this is the first thing to check.
How do I capture a group with regex_search?
In Ansible, pass the backreference as an extra argument, for example regex_search('v([0-9]+)', '1'), which returns a list of the captured groups. In a custom filter, accept a group index and return m.group(index).
Is template side regex a security risk?
It can be. Patterns built from untrusted input allow catastrophic backtracking, which stalls the process rendering the page. Escape user input with re.escape, keep patterns static in code, and never let a template compile an expression a visitor supplied.
The bottom line
If you are in Ansible, the filters exist and the only real trap is quoting. If you are anywhere else, spend fifteen lines registering your own and you get the same syntax with behaviour you control. Then use them sparingly, because the best place for a regular expression is almost always in the Python code that builds the context, not in the template that displays it.
About this article: GeekBlog covers U.S. technology news, AI, phones, smartwatches and gaming. Every story is written and checked under our Editorial Policy. Spotted a mistake or have a story tip? Contact our editors.

