From 6cc6fcf10ca3d87a9055c6611c853140cfce7d4d Mon Sep 17 00:00:00 2001 From: Erik Johnson Date: Thu, 9 Jan 2025 11:33:07 -0600 Subject: [PATCH] Improve docs on regex filters When capture groups are not used, the filter will always return something that will always evaluate as boolean False (because lack of capture groups means an empty tuple is returned for regex matches). This commit improves the docs, clarifying this and recommending how to use this filter to correctly identify if the pattern matched. --- doc/topics/jinja/index.rst | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/doc/topics/jinja/index.rst b/doc/topics/jinja/index.rst index ad8e436a00a5..79d88c4f149b 100644 --- a/doc/topics/jinja/index.rst +++ b/doc/topics/jinja/index.rst @@ -405,8 +405,9 @@ This text will be wrapped in quotes. .. versionadded:: 2017.7.0 -Scan through string looking for a location where this regular expression -produces a match. Returns ``None`` in case there were no matches found +Looks for a match for the specified regex anywhere in the string. If the string +does not match the regex, this filter returns ``None``. If the string _does_ +match the regex, then the `capture groups`_ for the regex will be returned. Example: @@ -420,6 +421,29 @@ Returns: ("defabcdef",) +If the regex you use does not contain a capture group then the number of +capture groups will be zero, and a matching regex will return an empty tuple. +This means that the following ``if`` statement would evaluate as ``False``: + +.. code-block:: jinja + + {%- if 'foobar' | regex_search('foo') %} + +If you do not need a capture group and are just looking to test if a string +matches a regex, then you should check to see if the filter returns ``None``: + +.. code-block:: jinja + + {%- if (some_var | regex_search('foo')) is not none %} + +.. note:: + + In a Jinja statement, a null value (i.e. a Python ``None``) should be + expressed as ``none`` (i.e. lowercase). More info on this can be found in + the **Note** section here in the `jinja docs`_. + +.. _`capture groups`: https://docs.python.org/3/library/re.html#re.Match.groups +.. _`jinja docs`: https://jinja.palletsprojects.com/en/stable/templates/#literals .. jinja_ref:: regex_match @@ -428,8 +452,8 @@ Returns: .. versionadded:: 2017.7.0 -If zero or more characters at the beginning of string match this regular -expression, otherwise returns ``None``. +Works exactly like :jinja_ref:`regex_search`, but only checks for matches at +the _beginning_ of the string passed into this filter. Example: