How to use ansible regex to display nth matches?

by mallory_cormier , in category: Third Party Scripts , 4 months ago

How to use ansible regex to display nth matches?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 4 months 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).

Related Threads:

How to get multiple first matches from regex?
How to filter distinct regex matches with sparql?
How to find specific matches in a string using regex?
How to use ansible with vagrant locally?
How to use regex with numbers?
How to use regex in mongodb query?