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

How to pick out a particular group of numbers in a string

I have a string (which is different everytime but follows a similar format):

54321.0 67778.0000002 0.3673987009 1 1017.750 88.370 512 7 1 H8711-3040

I’m trying to use regular expressions to be able to pick out any one of those entries in my python code, but I’m struggling.

I’m trying

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

testRegex = re.compile(r'\w.+\w')
out = testRegex.search('# 53421.0 67778.0000002 0.3673987009 1 1517.750 88.370 512 7 1 J1745-3040')
print(out.group())

But I’m just getting the whole line returned. I can see why it does that but not sure how to just pick out "512" for example (whatever number might be in its place).

>Solution :

You can use

re.findall(r'\b\w(?:\S*\w)?\b', s) 

See the regex demo. Details:

  • \b – a word boundary
  • \w – a word char
  • ?:\S*\w)? – an optional sequence of any zero or more non-whitespace chars and then a word char
  • \b – a word boundary

See the Python demo:

import re
s = '# 53421.0 67778.0000002 0.3673987009 1 1517.750 88.370 512 7 1 J1745-3040'
print( re.findall(r'\b\w(?:\S*\w)?\b', s) )
# => ['53421.0', '67778.0000002', '0.3673987009', '1', '1517.750', '88.370', '512', '7', '1', 'J1745-3040']
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