From 6607051b75bc308ac9cef4ddfb9c86da4046bdda Mon Sep 17 00:00:00 2001 From: Martin Krizek Date: Sat, 31 Jul 2021 01:08:03 +0200 Subject: [PATCH] docs: clarify regex_search return value (#75343) --- .../rst/user_guide/playbooks_filters.rst | 17 +++++++++++++---- .../targets/filter_core/tasks/main.yml | 2 ++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/docsite/rst/user_guide/playbooks_filters.rst b/docs/docsite/rst/user_guide/playbooks_filters.rst index 0d6528b8ed6..5e66c84532f 100644 --- a/docs/docsite/rst/user_guide/playbooks_filters.rst +++ b/docs/docsite/rst/user_guide/playbooks_filters.rst @@ -1505,10 +1505,6 @@ To search in a string or extract parts of a string with a regular expression, us {{ 'server1/database42' | regex_search('database[0-9]+') }} # => 'database42' - # Returns an empty string if it cannot find a match - {{ 'ansible' | regex_search('foobar') }} - # => '' - # Example for a case insensitive search in multiline mode {{ 'foo\nBAR' | regex_search('^bar', multiline=True, ignorecase=True) }} # => 'BAR' @@ -1521,6 +1517,19 @@ To search in a string or extract parts of a string with a regular expression, us {{ '21/42' | regex_search('(?P[0-9]+)/(?P[0-9]+)', '\\g', '\\g') }} # => ['21', '42'] +The ``regex_search`` filter returns an empty string if it cannot find a match:: + + {{ 'ansible' | regex_search('foobar') }} + # => '' + +Note that due to historic behavior and custom re-implementation of some of the Jinja internals in Ansible there is an exception to the behavior. When used in a Jinja expression (for example in conjunction with operators, other filters, and so no) the return value differs, in those situations the return value is ``none``. See the two examples below:: + + {{ 'ansible' | regex_search('foobar') == '' }} + # => False + {{ 'ansible' | regex_search('foobar') == none }} + # => True + +When ``jinja2_native`` setting is enabled, the ``regex_search`` filter always returns ``none`` if it cannot find a match. To extract all occurrences of regex matches in a string, use the ``regex_findall`` filter:: diff --git a/test/integration/targets/filter_core/tasks/main.yml b/test/integration/targets/filter_core/tasks/main.yml index 567a27f10ed..c637fc1754c 100644 --- a/test/integration/targets/filter_core/tasks/main.yml +++ b/test/integration/targets/filter_core/tasks/main.yml @@ -283,6 +283,7 @@ multi_line: "{{ 'hello\nworld' | regex_search('^world', multiline=true) }}" named_groups: "{{ 'goodbye' | regex_search('(?Pgood)(?Pbye)', '\\g', '\\g') }}" numbered_groups: "{{ 'goodbye' | regex_search('(good)(bye)', '\\2', '\\1') }}" + no_match_is_none_inline: "{{ 'hello' | regex_search('world') == none }}" - name: regex_search unknown argument (failure expected) set_fact: @@ -299,6 +300,7 @@ - multi_line == 'world' - named_groups == ['bye', 'good'] - numbered_groups == ['bye', 'good'] + - no_match_is_none_inline - failure is failed - name: Verify to_bool