Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible, Regular Expression for first character of string

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?

like image 927
Squiggs. Avatar asked Dec 19 '25 08:12

Squiggs.


1 Answers

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).
like image 52
Wiktor Stribiżew Avatar answered Dec 21 '25 01:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!