2

I'm trying to extract the digits from a string.

For example, if I have the string 'host2' I want only the '2' returned. If there is no digit in the string, I want '1' returned.

Some examples:

host1 -> 1
ho12st -> 12
host -> 1
host2 -> 2
host2test -> 2
host02 -> 02
host34 -> 34

I don't know if I should use a module for this, or use internal workings and just set a fact. I'm a bit of a newb.

Something like the following works in python, but not ansible.

int(''.join(filter(str.isdigit, {{ ansible_hostname }} )))

This ends up interpreted on the shell so I can't use the {{ ansible_hostname }} variable. It also doesn't default to '1' if no digits are found.

**** Answer ****

I ended up using this to get my required result:

- set_fact:
        env_id: '{{ server_name | regex_search(qry) }}'
      vars:
        qry: '[0-9]'
    - set_fact:
        env_id: "1"
      when: env_id == ""
user3299633
  • 2,971
  • 3
  • 24
  • 38
  • 4
    Possible duplicate of [How to extract numbers from a string in Python?](https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python), then just check to see if a match exists and return 1 otherwise – Xosrov Jun 07 '19 at 20:48
  • 2
    I didn't manage to answer, so I comment. With ansible, you can do this: "{{ server_name | regex_replace('[^0-9]', '') }}" – Romain DEQUIDT Nov 19 '19 at 23:50

1 Answers1

0

If you'd like to do this task with regular expressions, my guess is that we would be only get those with digits, with a simple expression such as:

([0-9]+)

Demo

and then you can simply add an if, for those without digits to return 1.

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([0-9]+)"

test_str = ("host1\n"
    "ho12st\n"
    "host\n"
    "host2\n"
    "host2test\n"
    "host02\n"
    "host34")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Emma
  • 27,428
  • 11
  • 44
  • 69