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 multiple substrings from one string

I have the following string which I am parsing from another file :
"CHEM1(5GL) CH3M2(55LB) CHEM3954114(50KG)"
What I want to do is split them up into individual values, which I achieve using the .split() function. So I get them as an array:

x = ['CHEM1(5GL)', 'CH3M2(55LB)','CHEM3954114(50KG)']

Now I want to further split them into 3 segments, and store them in 3 other variables so I can write them to excel as such :

a = CHEM1
b = 5
c = GL

for the first array, then I will loop back for the second array:

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

a = CH3M2
b = 55
c = LB

and finally :

a = CHEM3954114
b = 50
c = KG

I am unsure how to go about that as I am still new in python. To the best of my acknowledge I iterate multiple times with the split function, but I believe there has to be a better way to do it than that.

Thank you.

>Solution :

You should use the re package:

import re

x = ['CHEM1(5GL)', 'CH3M2(55LB)','CHEM3954114(50KG)']

pattern = re.compile("([^\(]+)\((\d+)(.+)\)")

for x1 in x:
    m = pattern.search(x1)
    if m:
        a, b, c = m.group(1), int(m.group(2)), m.group(3)
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