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

Regular Expression in Python by Matches

I have a list of numbers that I am trying to pull out of text. Here is what I am working with:

Expression = r"(\d+\.)?(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)"
ExpressionResult = (re.findall(Expression, str(OriginalString)))
print('original')
print(str(OriginalString))
print('parsed')
print(str(ExpressionResult))

Here is my output:

original
['', '', '7', '', '', '', '9.2', '', '', '', '9.1', '', '', '', '9.2', '', '', '', '9.5.5', '', '', '', '9.5', '', '', '', '10.1.1', '', '', '', '10.1', '', '', '']
parsed
[('', '', '', '', '7'), ('9.', '', '', '', '2'), ('9.', '', '', '', '1'), ('9.', '', '', '', '2'), ('9.', '5.', '', '', '5'), ('9.', '', '', '', '5'), ('10.', '1.', '', '', '1'), ('10.', '', '', '', '1')]

It looks like the expression is being split up by groups rather than matches. How do I get the match?

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

Expected output:

7, 9.2, 9.1, 9.2, 9.5.5, 9.5, 10.1.1, 10.1

>Solution :

Not exactly sure why you are using regex?
Just use list comprehension to create new list, and if needed join the list using the .join() function:

OriginalString = ['', '', '7', '', '', '', '9.2', '', '', '', '9.1', '', '', '', '9.2', '', '', '', '9.5.5', '', '', '', '9.5', '', '', '', '10.1.1', '', '', '', '10.1', '', '', '']

ExpressionResult = [x for x in OriginalString if x != '']
print(", ".join(ExpressionResult))

OUTPUT:

7, 9.2, 9.1, 9.2, 9.5.5, 9.5, 10.1.1, 10.1
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