Home > Software engineering >  Ansible, Regular Expression for first character of string
Ansible, Regular Expression for first character of string

Time:06-11

I currently have an Ansible regex that doesn't seem to be working, despite a regex working over here: https://regex101.com/r/g36zkI/1

Essentially, the problem is as follows: last_name can be double barelled, and I want to extract the first letter of each of the words contained within it. Regex seems like best way forward. Just can't get Jinja to do its thing.

The above seems to extract the first character in the word boundary:

Input:
first_name: Pepper
last_name: Von Pig

Jinja:
backup_username: "{{ first_name }}{{ last_name | regex_search('([a-zA-Z]|\d )') }}"

Desired Output: PepperVP

Problem / playground illustrated here:

https://jinjafx.io/dt/pvQ7oWx3Q

What am I missing here?

CodePudding user response:

You can use

backup_username: "{{ first_name }}{{ last_name | regex_findall('\\b[A-Z]') | join }}

The regex_findall('\\b[A-Z]') can be replaced with regex_findall('\\b[A-Za-z]') or regex_findall('\\b\\w') (depending on real life requirements).

Details:

  • regex_findall('\\b[A-Z]') - extracts all occurrences of an uppercase letter at the start of string or preceded with a non-word char
  • join - joins the items from the previous step with an empty string (=concatenates the items).
  • Related