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

Python – Extract list substring from list with regex

I am trying to extract a list from a string, for example, the list always behind id=000-

l = "machine status: id=000-[{'89c57212e14694d3488e3924c46219dc_2': True}, {'45b5eab7caf0773f07a5f3a1b9f0c545_2': True}]"

My desired output should be list of dict

"[{'89c57212e14694d3488e3924c46219dc_2': True}, {'45b5eab7caf0773f07a5f3a1b9f0c545_2': True}]"

However with my regex

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

re.findall(r'(id=000-\[.*\])', l)

I got output below, which included the id=000 prefix

["id=000-[{'89c57212e14694d3488e3924c46219dc_2': True}, {'45b5eab7caf0773f07a5f3a1b9f0c545_2': True}]"]

>Solution :

Simply use a "positive lookbehind", which is with (?<=pattern):

import re

l = "machine status: id=000-[{'89c57212e14694d3488e3924c46219dc_2': True}, {'45b5eab7caf0773f07a5f3a1b9f0c545_2': True}]"

for result in re.findall(r'(?<=id=000-)\[.*\]', l):
    print(result)

Output:

[{'89c57212e14694d3488e3924c46219dc_2': True}, {'45b5eab7caf0773f07a5f3a1b9f0c545_2': True}]
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