繁体   English   中英

Ansible 或 Python,如何在列表中使用 regex_findall 来返回以特定模式开头的单词

[英]Ansible or Python, how to use regex_findall on a list to return words that start with a certain pattern

我主要在 ansible 中使用它,但我认为它在 python 中类似。 所以我有一个字符串列表,我需要从中提取以某种模式开头的单词。 例如,如果我有以下内容:

list1: ['water_3gallons_6/20/22   490832', 'applejuice_1liter_6/18/22    490833', 'soda_2liters_6/22/22     490834', 'water_1gal_today      490835']

# and lets say I only want to pull the words that start with water (ignoring the 490832 part)
# meaning it should return this list: ['water_3gallons_6/20/22','water_1gal_today']

# I was using the following 2 codes and it was returning an empty list

- name: "Create list of words that start with water from list1 variable"
  set_fact:
     start_with_water: "{{ list1 |regex_findall('^water') }}" # RETURNED EMPTY LIST

- name: "Create list of words that start with water from list1 variable"
  set_fact:
     start_with_water: "{{ list1 |regex_findall('\\Awater') }}" # RETURNED EMPTY LIST TOO

编辑:根据新要求更新

虽然 Frenchy 的回答没有错,但它本质上会比 Jinja2 想要通过|select filter完成的方式更慢并且更冗长,该过滤器专为处理列表项而设计:

- set_fact:
     start_with_water: >-
       {{ list1 | select('match', '^water')
       | map('regex_findall', '([^ ]+) .*')
       | map('first')
       | list }}

生产

{
  "ansible_facts": {
    "start_with_water": [
      "water_3gallons_6/20/22",
      "water_1gal_today"
    ]
  },
  "changed": false
}

如果您好奇为什么您使用regex_findall的方法没有达到您的预期,那是因为该过滤器需要一个字符串输入,所以 jinja2 有帮助(?)通过调用str(list1)list[str]强制转换为str并将输入过滤器与您预期的任何“行首”都不匹配

regex_findall用于字符串:

  tasks:
    - name: get data
      set_fact:
        start_with_water: "{{ start_with_water | d([]) + [item] }}"
      loop: "{{ list1 }}"
      when: item | regex_findall('^water')
    - name: display
      debug:
        msg: "{{ start_with_water }}"

结果:

ok: [localhost] => {
    "msg": [
        "water_3gallons_6/20/22   490832",
        "water_1gal_today      490835"
    ]
}

为避免when条件,您可以直接在列表中使用select

  tasks:
    - set_fact:
        start_with_water: "{{ list1|select('regex', '^water')|list }}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM