在ansible中打印子字符串的匹配数

在ansible中打印子字符串的匹配数,ansible,Ansible,我试图在ansible变量中打印匹配子字符串的数目。在下面的示例中,我试图打印2,因为abc在变量vara中出现了两次。并打印3,因为在检查变量varb时,abc出现三次 --- - hosts: localhost vars: vara: 'abc1\nabcdef' varb: 'def abc and abcd and abc' tasks: - debug: var=vara|regex_search('abc') - name: "Run thi

我试图在ansible变量中打印匹配子字符串的数目。在下面的示例中,我试图打印
2
,因为
abc
在变量
vara
中出现了两次。并打印
3
,因为在检查变量
varb
时,
abc
出现三次

---
- hosts: localhost
  vars:
    vara: 'abc1\nabcdef'
    varb: 'def abc and abcd and abc'


  tasks:
   - debug: var=vara|regex_search('abc')
   - name: "Run this task when its condition in true"
     shell: echo abc in vara
     when:  (vara|regex_search('abc')) == 2
根据状态,您必须将
regex\u findall
过滤器与
length
功能结合使用
regex\u findall
返回列表中所有出现的
regex
length
过滤器返回列表中的元素数

---
- hosts: localhost
  vars:
    vara: 'abc1\nabcdef'
    varb: 'def abc and abcd and abc'
  tasks:
   - debug: var=vara|regex_findall('abc')|length
   - debug: var=varb|regex_findall('abc')|length
   - name: "Run this task when its condition in true"
     debug: msg='abc in vara'
     when:  (vara|regex_findall('abc')|length) == 2
   - name: "Run this task when its condition in true"
     debug: msg='abc in varb'
     when:  (varb|regex_findall('abc')|length) == 2
输出

PLAY [localhost] ***************************************************************

TASK [debug] *******************************************************************
ok: [localhost] => {
    "vara|regex_findall('abc')|length": "2"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "varb|regex_findall('abc')|length": "3"
}

TASK [Run this task when its condition in true] ********************************
ok: [localhost] => {
    "msg": "abc in vara"
}

TASK [Run this task when its condition in true] ********************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0

我收到了
“msg”:“在({{var1 | regex_findall('mystring')| length}})上发生了意外的模板类型错误”:预期的字符串或缓冲区“
@monk var1必须是字符串。您可以使用类型_debug-
{{var1 |类型_debug}}