How to use ansible regex to display nth matches?

by mallory_cormier , in category: Third Party Scripts , 15 days ago

How to use ansible regex to display nth matches?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 14 days ago

@mallory_cormier 

You can use the regex_search filter in Ansible to display nth matches in a string. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
- name: Display nth match using regex_search
  hosts: localhost
  tasks:
    - name: Set a string containing multiple matches
      set_fact:
        my_string: "aaa123bbb456ccc789"

    - name: Display 2nd match
      debug:
        msg: "{{ my_string | regex_search('([0-9]+)', '\1', nth=2) }}


In the regex_search filter, the first argument is the regular expression pattern, the second argument is the capture group in the pattern to extract, and the nth parameter specifies which match to display (in this case, the 2nd match).