Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting numbers from a string with a special structure with regular expressions

I have a string with the structure

Resolution:  1200, Time: 16.255 (7.920 GFlop => 1487.23 MFlop/s, residual 0.007113, 500 iterations)

and I am trying to efficiently extract the floats from that string. As the stream of string does not only contain strings with this pattern but others as well. Is there a way to get the numbers from this string with the package re?

I am looking for a way like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import re

a = "Resolution:  1200, Time: 16.255 (7.920 GFlop => 1487.23 MFlop/s, residual 0.007113, 500 iterations)"

nbrs = re.match("Resolution:  \d, Time: \d (\d GFlop => \d MFlop/s, residual \d, \d iterations)"

where \d is an identifier for an arbitrary float? Or is the easiest way of doing this just to strip the string multiple times and check for specific contents?

>Solution :

import re
s = 'Resolution:  1200, Time: 16.255 (7.920 GFlop => 1487.23 MFlop/s, residual 0.007113, 500 iterations)'

p = re.findall(r'\d+[\.]\d+|\d+',s)
print(p)

OUTPUT:

['1200', '16.255', '7.920', '1487.23', '0.007113', '500']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading