我有一个名为somelist的字符串列表,如下所示。如何指定正则表达式来搜索字符串名称:bob-请注意,该名称不应该与名称:bobby匹配。我尝试使用^和$来指示字符串的开始,字符串的结束,但是它不起作用。另外,冒号还会导致以下错误:语法错误-在此上下文中不允许使用映射值。我不知道如何逃脱结肠。谢谢!
---
- hosts: localhost
vars:
somelist:
- "name: greg"
- "name: bobby"
- "name: joe"
tasks:
- debug: msg='{{ somelist is search("^name: bob$") }}' # <--- this should equate to false
- debug: msg='{{ somelist is search("^name: bobby$") }}' # <--- this should equate to true
使用选择并测试长度。例如
- debug:
msg: "{{ somelist|
select('search', '^name: bob$')|
list|length > 0 }}" # <--- this should equate to false
- debug:
msg: "{{ somelist|
select('search', '^name: bobby$')|
list|length > 0 }}" # <--- this should equate to true
给(删节)
msg: false
msg: true
Collon “:”不是Python regex特殊字符。不必逃避它。将正则表达式放入变量可以简化条件。例如,以下任务
- debug:
msg: bob is in the list
when: somelist|select('search', regex)|list|length > 0
vars:
regex: '^name: bob$'
- debug:
msg: bobby is in the list
when: somelist|select('search', regex)|list|length > 0
vars:
regex: '^name: bobby$'
给(删节)
skipping: [localhost]
ok: [localhost] =>
msg: bobby is in the list
可以避免使用正则表达式。例如,映射from_yaml,创建词典列表,然后选择attattr。以下任务给出相同的结果
- debug:
msg: "{{ somelist|
map('from_yaml')|
selectattr('name', 'eq', 'bob')|
list|length > 0 }}"
- debug:
msg: "{{ somelist|
map('from_yaml')|
selectattr('name', 'eq', 'bobby')|
list|length > 0 }}"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句