-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?

3
  • Read up on Reference - What does this regex mean? Commented Jul 24, 2020 at 12:07
  • "test_program:5.4.3.2.11111".split(":")[1] gives "5.4.3.2.11111" Commented Jul 24, 2020 at 12:34
  • ".".join(['5', '4', '3', '2', '11111']) gives "5.4.3.2.11111" Commented Jul 24, 2020 at 12:36

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for help!
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.