How to extract with regexp in ansible numbers from hostname without one specific

Viewed 1426

How I can extract with regexp from hostname number without one from domain. Examples:

nginx-node-01.prd1.com
nginx-node-10.prd1.com

And I need extract only number after nginx-node-, without number from "prd".

When I do this regexp

{{ inventory_hostname | regex_replace('[^0-9]') }}

I get output like this

011
101

Thanks for any help!

2 Answers

Instead of removing all non digits, you can match the format of the string and capture the digits in a group, and use that group in the replacement.

^\w+(?:-\w+)+-(\d+)\.\S+$

The pattern matches:

  • ^ Start of string
  • \w+ Match 1+ word characters
  • (?:-\w+)+ Repeat 1+ times a - and 1+ word characters
  • -(\d+) Match - and capture 1+ digits in group 1
  • \.\S+ match 1 . and 1+ non whitespace chars
  • $ End of string

Regex demo

Output

01
10

For example

{{ inventory_hostname | regex_replace('^\\w+(?:-\\w+)+-(\\d+)\\.\\S+$', '\\1') }}

Another option might be regex_search and match 1+ digits between - and . using lookarounds.

(?<=-)\\d+(?=\\.)

Regex demo

Since these strings look very well-structured, you may leverage that and simply remove all chars from the beginning till the first digit with ^\D+ pattern and all chars till the end of string from the first dot using \..* pattern, combined with the | alternation operator:

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

See the regex demo.

Details:

  • ^ - start of string
  • \D+ - one or more chars other than a digit
  • | - or
  • \. - a dot
  • .* - any zero or more chars other than line break chars as many as possible.
Related