从 ansible 变量中过滤匹配模式的子字符串,并将匹配的子字符串分配给另一个变量

Filter a substring matching a pattern from an ansible variable and assign matched substring to another variable

假设我们有一个长字符串变量 mystr。我们有一个正则表达式模式 substr_pattern,匹配此模式的子字符串将从 mystr 中过滤掉并分配给另一个变量 substrplaybook_filters 上的文档似乎没有明显的方法可以在 ansible 中执行此操作,尽管使用 python 本身的 re 模块很简单。

ansible 文档中给出了 3 种方法,其中 none 似乎解决了我的问题:

  1. match:这个过滤器returns true/false取决于整个模式是否匹配整个字符串但不return匹配group/substring.

  2. search:用于过滤较大字符串中的substr。但是像match,只有returns true/false,没有匹配到这里需要的group/substring

  3. regex_replace:这用于将字符串中的匹配模式替换为另一个字符串。但是不清楚如何将匹配到的pattern对应的substring/group注册到一个新的变量中

有什么我遗漏的吗?或者这是 ansible 中缺少的功能?

Ansible 版本:2.1

示例:

mystr: "This is the long string. With a url. http://example.org/12345"
pattern: "http:\/\/example.org\/(\d+)"
substr: 12345   # First matched group i.e. \1

总结:如何从mystr中获取匹配pattern的子字符串并将其注册到一个ansible变量substr?

如果可以修改模式,则可以使用 regex_replace 过滤器并仅用匹配的数字替换整个字符串。

mystr | regex_replace('^.*http:\/\/example.org\/(\d+).*?$', '\1')

要将结果分配给新变量,您可以使用 set_fact 模块。

- set_fact:
    substr: "{{ mystr | regex_replace('^.*http:\/\/example.org\/(\d+).*?$', '\1') }}"