簡體   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