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

using regex to extract numbers

So, I have this string

{"orders":[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},
{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":648},{"id":649},
{"id":650},{"id":651},{"id":652},{"id":653}],
"errors":[{"code":3,"message":"[PHP Warning #2] count(): Parameter must be an 
array or an object that implements Countable (153)"}]}

And I need to extract the numbers. Any idea on how to solve this?

Thanks!

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

>Solution :

An integer is simply 1+ digits, so the regular expression that accepts integer is [0-9]+.

import re

string = """{"orders":[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":648},{"id":649},{"id":650},{"id":651},{"id":652},{"id":653}],"errors":[{"code":3,"message":"[PHP Warning #2] count(): Parameter must be an array or an object that implements Countable (153)"}]}"""

search_results = re.findall(r"[0-9]+", string)

This gives:

>>> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '648', '649', '650', '651', '652', '653', '3', '2', '153']

You can map the results through a int function or whatever (map(int, search_results)) if what you’re looking for is a list of integers.

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