ansible.builtin.regex_replace 过滤器 – 使用正则表达式替换字符串

注意

此过滤器插件是 ansible-core 的一部分,包含在所有 Ansible 安装中。在大多数情况下,您可以使用简短的插件名称 regex_replace。但是,我们建议您使用 完全限定的集合名称 (FQCN) ansible.builtin.regex_replace,以便轻松链接到插件文档并避免与可能具有相同过滤器插件名称的其他集合发生冲突。

概要

  • 根据第一个匹配项,使用另一个正则表达式定义的字符串替换正则表达式定义的子字符串。

输入

这描述了过滤器的输入,即 | ansible.builtin.regex_replace 之前的数值。

参数

注释

输入

字符串 / 必需

要匹配的字符串。

位置参数

这描述了过滤器的 位置参数。这些是在以下示例中的 positional1positional2 等值:input | ansible.builtin.regex_replace(positional1, positional2, ...)

参数

注释

_regex_match

整数 / 必需

定义匹配的正则表达式字符串。

_regex_replace

整数 / 必需

定义替换的正则表达式字符串。

关键字参数

这描述了过滤器的关键字参数。这些是在以下示例中的 key1=value1key2=value2 等值:input | ansible.builtin.regex_replace(key1=value1, key2=value2, ...)

参数

注释

count

整数

在 ansible-core 2.17 中添加

要替换的模式出现次数的最大值。如果为零,则替换所有出现。

默认值: 0

ignorecase

布尔值

如果 True,则强制搜索不区分大小写,否则区分大小写。

选项

  • false ← (默认)

  • true

mandatory_count

整数

在 ansible-core 2.17 中添加

预期一定的替换次数。否则引发错误。如果为零,则忽略。

默认值: 0

multiline

布尔值

如果 True,则跨行尾搜索,否则不跨行尾搜索。

选项

  • false ← (默认)

  • true

备注

注意

  • 当同时使用关键字参数和位置参数时,位置参数必须列在关键字参数之前:input | ansible.builtin.regex_replace(positional1, positional2, key1=value1, key2=value2)

  • 映射到 Python 的 re.sub

  • 组匹配的子字符串可以通过符号组名或 ``\{number}`` 特殊序列访问。参见示例部分。

示例

# whatami => 'able'
whatami: "{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}"

# commalocal => 'localhost, 80'
commalocal: "{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}"

# piratecomment => '#CAR\n#tar\nfoo\n#bar\n'
piratecomment: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('^(.ar)$', '#\\1', multiline=True, ignorecase=True) }}"

# Using inline regex flags instead of passing options to filter
# See https://docs.pythonlang.cn/3/library/re.html for more information
# on inline regex flags
# piratecomment => '#CAR\n#tar\nfoo\n#bar\n'
piratecomment: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('(?im)^(.ar)$', '#\\1') }}"

# 'foo=bar=baz' => 'foo:bar=baz'
key_value: "{{ 'foo=bar=baz' | regex_replace('=', ':', count=1) }}"

返回值

描述

返回值

字符串

包含替换的字符串(如果无匹配项,则为原始字符串)。

返回:成功

提示

每个条目类型的配置条目具有从低到高的优先级顺序。例如,列表中较低的变量将覆盖较高的变量。