Ansible regex_replace- ho to extract specific value

Viewed 259

How I can extract this value from hostname with regex_replace like this.

I have regex_replace

"{{ inventory_hostname | regex_replace('^\\D+|\\..*', '') }}"

And hostname like this

nginx09-2.domain.com

And I want extract only number after - (2), but my regex_replace extracing 09-2.

2 Answers

You can capture the number and replace the string with it:

"{{ inventory_hostname | regex_replace('^.*-(\\d+).*$', '\\1') }}"

- debug:
    msg: "{{ 'nginx09-2.domain.com' | regex_replace('^.*-(\\d+).*$', '\\1') }}"

# 2

You can extend your pattern a bit to match the first number and -

"{{ inventory_hostname | regex_replace('^\\D+\\d+-|\\..*', '') }}"

See the regex demo

Details

  • ^\D+\d+- - a start of string (^), then one or more chars other than a digit (\D+), then one or more digits (\d+) and a - char
  • | - or
  • \..* - a dot (\.) and then the rest of the string (.*).
Related