-4

How can I format output from regex or return regex output in specific format.

For example: I have a program test_program:5.4.3.2.11111

and I want to obtain only this value: 5.4.3.2.11111

If I use this function:

import re

get_number = "test_program:5.4.3.2.11111"
number = re.findall('\d+', get_number)

the output is:

['5', '4', '3', '2', '11111']

but I cannot pass it to another variable due to incorrect formatting.

I've use something like this:

import re

get_number = re.compile(r'\d.\d.\d.d.\d\d\d\d\d')
number = get_number.search('test_program:5.4.3.2.11111')
print(number.group())

and the output is in the correct format but if any number changes ex 5 will change to 10 or 11111 will change to 1111112, this will not work correctly.

Is there any better solution to obtain number from string in proper format that will not be vurnable to changes?

Solaire
  • 113
  • 4

2 Answers2

5

Try this regex to obtain the desired result

import re

get_number = "test_program:5.4.3.2.11111"
number = re.findall('[\d.]+', get_number)
1

You can use repeaters for the \d values so they match 1 or more times (instead of exactly one time):

import re


get_number = re.compile(r'\d+.\d+.\d+.\d+.\d+')
number = get_number.search('test_program:15.4.3.2.111112')
print(number.group())

>>> 15.4.3.2.111112
Ronald
  • 2,930
  • 2
  • 7
  • 18