可靠的Regex搜索



我正在尝试使用正则表达式搜索来解析句子列表中的字符串。

我的句子列表:

- my name is 'Andi', nice to meet you
- hello my name is 'Bella', hi!
- this is 'Cain'

我想要的输出:

- Andi
- Bella
- Cain

我尝试过的:

- set_fact:
test: >-
{{
sentences | map("regex_search", "is '(.*)'", "1") | flatten
}}
vars:
sentences:
- my name is 'Andi', nice to meet you
- hello my name is 'Bella', hi!
- this is 'Cain'

这给了我想要的东西,那就是:

- Andi
- Bella 
- Cain

我的问题是当我的数据是这样的时候:

- my name is 'Andi', nice to meet you
- hello i am me!
- hello my name is 'Love', hi!
- this is 'Cain'

我希望它能显示这样的结果:

- Andi
- Love
- Cain

但它跳过了不匹配字符串之后的所有内容,并显示如下结果:

- Andi

如何只跳过不匹配的行而不跳过所有行?

简而言之,以下sentence.yml剧本:

---
- hosts: localhost
gather_facts: false
vars:
sentences:
- my name is 'Andi', nice to meet you
- hello i am me!
- hello my name is 'Love', hi!
- this is 'Cain'
name_regex: "^.*is '(.*)'.*$"
names: '{{ sentences | select("regex", name_regex) |  map("regex_replace", name_regex, "g<1>") | flatten }}'
tasks:
- debug:
var: names

给出:

$ ansible-playbook sentence.yml 
PLAY [localhost] **************************************************************************************************************************************************************************************************
TASK [debug] ******************************************************************************************************************************************************************************************************
ok: [localhost] => {
"names": [
"Andi",
"Love",
"Cain"
]
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

最新更新