使用Ansible的regex_search
过滤器可以在列表中搜索特定字符串的正则表达式。下面是一个包含代码示例的解决方法:
- hosts: localhost
vars:
my_list:
- "apple"
- "banana"
- "orange"
- "grapefruit"
tasks:
- name: Search for specific string using regex
debug:
msg: "{{ item }}"
loop: "{{ my_list }}"
when: item | regex_search('a.*e')
在这个示例中,我们有一个包含水果名称的列表my_list
。我们使用loop
循环遍历列表中的每个元素,并使用regex_search
过滤器来检查每个元素是否与正则表达式a.*e
匹配。如果匹配成功,则打印该元素。
运行以上代码将输出以下结果:
TASK [Search for specific string using regex] ***********************************************************************
ok: [localhost] => (item=apple) => {
"msg": "apple"
}
ok: [localhost] => (item=grapefruit) => {
"msg": "grapefruit"
}
在这种情况下,只有元素"apple"和"grapefruit"匹配正则表达式a.*e
,因此只有这两个元素被打印出来。